0

所以我的问题是页面的美感一直有效,直到您点击提交按钮(它有效,因为有一个加载图像设置为在通过 jquery.contact.js 单击按钮后出现)。但是,它停留在加载图像处,不会返回一条消息说提交成功,也不会 PUT 到我的数据库中,也不会发送确认电子邮件(忽略)。

我想知道出了什么问题以及如何解决它,如果可能的话,请一对一完成,以便我可以快速完成?

这是脚本:

索引.php

<div id="contact">
        <h1>Contact us</h1>
          <form id="ContactForm" action="">
            <p>
                <label>Name</label>
                <input id="name" name="name" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
                <span class="error" style="display:none;"></span>
            </p>
            <p>
                <label>Email</label>
                <input id="email" name="email" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
                <span class="error" style="display:none;"></span>
            </p>
            <p>
                <label>Phone Number<span>(optional)</span></label>
                <input id="phone" name="phone" class="inplaceError" maxlength="120" type="text" autocomplete="off"/>
            </p>
            <p class="submit">
                <input id="send" type="button" name= "submit" value="Submit"/>
                <span id="loader" class="loader" style="display:none;"></span>
                <span id="success_message" class="success"></span>
            </p>
            <input id="newcontact" name="newcontact" type="hidden" value="1"></input>
        </form>
    </div>
    <div class="envelope">
        <img id="envelope" src="images/envelope.png" alt="envelope" width="246" height="175" style="display:none;"/>
    </div>
    <!-- The JavaScript -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="javascript/jquery.contact.js" type="text/javascript"></script>

联系方式.php

ini_set('display_errors', 1); error_reporting(E_ALL);

require_once("db.php");                 /* Database Class */
require_once('utils/is_email.php');     /* Email Validation Script */



/* Handle Ajax Request */
if(isset($_POST['newcontact'])){
$contact = new Contact();
unset($contact);
}
else{
header('Location: /');
}

/* Class Contact */
class Contact{

private $db;                        /* the database obj */

private $errors         = array();  /* holds error messages */
private $num_errors;                /* number of errors in submitted form */

public function __construct(){
    $this->db = new DB();
    if(isset($_POST['submit']))
        $this->processNewMessage();
    else
        header("Location: /");
}

public function processNewMessage(){

    $email      = $_POST['email'];
    $name       = $_POST['name'];
    $phone      = $_POST['phone'];

    /* Server Side Data Validation */

    /* Email Validation */
    if(!$email || mb_strlen($email = trim($email)) == 0)
        $this->setError('email','required field');
    else{
        if(!is_email($email))
            $this->setError('email', 'invalid email');
        else if(mb_strlen($email) > 120)
            $this->setError('email', 'too long! 120');
    }

    /* Name Validation */
    if(!$name || mb_strlen($name = trim($name)) == 0)
        $this->setError('name', 'required field');
    else if(mb_strlen(trim($name)) > 120)
        $this->setError('name', 'too long! 120 characters');

    /* Website Validation */
    if(!mb_eregi("^[a-zA-Z0-9-#_.+!*'(),/&:;=?@]*$", $phone))
        $this->setError('phone', 'invalid website');    
    elseif(mb_strlen(trim($phone)) > 40)
        $this->setError('phone', 'too long! max 40 characters');

    /* Errors exist */
    if($this->countErrors() > 0){
        $json = array(
            'result' => -1, 
            'errors' => array(
                            array('name' => 'email'     ,'value' => $this->error_value('email')),
                            array('name' => 'name'      ,'value' => $this->error_value('name')),
                            array('name' => 'phone'     ,'value' => $this->error_value('phone')),
                        )
            );              
        $encoded = json_encode($json);
        echo $encoded;
        unset($encoded);
    }
    /* No errors, insert in db*/
    else{
        if(($ret = $this->db->dbNewMessage($email, $name, $website, $message)) > 0){
            $json = array('result'      => 1); 
            if(SEND_EMAIL)
                $this->sendEmail($email,$name,$phone);
        }   
        else
            $json = array('result'      => -1); /* something went wrong in database insertion  */
        $encoded = json_encode($json);
        echo $encoded;
        unset($encoded);
    }
}

public function sendEmail($email,$name,$website,$message){
    /* Just format the email text the way you want ... */
    $message_body       = "Hello from www.masterplanme.com, ".$name."! \n (".$email." - ".$phone.") \n You are receiving this message because you have recently completed a contact fcrm with us. We will let you know of any updates to come in the near future. Thank you! \n \n \n DO NOT REPLY.";
    $headers            = "From Quantum Leap";

    return mail($email,MESSAGE_SUBJECT,$message_body,$headers);
}

public function setError($field, $errmsg){
    $this->errors[$field]   = $errmsg;
    $this->num_errors       = count($this->errors);
}

public function error_value($field){
    if(array_key_exists($field,$this->errors))
        return $this->errors[$field];
    else
        return 'ERROR';
}

public function countErrors(){
    return $this->num_errors;
}
};

数据库.php

require_once("config.php"); /* Configuration File */

class DB{

private $link;

public function __construct(){
    $this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME) OR die('Could not connect to MySQL: '.mysqli_connect_error()); 
}

public function __destruct() {
    mysqli_close($this->link);
}

public function dbNewMessage($email,$name,$website,$message){
    $email      = mysqli_real_escape_string($this->link,$email);
    $name       = mysqli_real_escape_string($this->link,$name);
    $phone      = mysqli_real_escape_string($this->link,$phone);

    mysqli_autocommit($this->link,FALSE);

    $query = "INSERT INTO CONTACT(pk_contact,name,email,phone) 
              VALUES('NULL','$name','$email','$phone')";
    mysqli_query($this->link,$query);

    if(mysqli_errno($this->link))
        return -1;
    else{
        mysqli_commit($this->link);
        return 1;
    }
}   
};

jquery.contact.js

$(document).ready(function() {
contact.initEventHandlers();
});
var contact = {
initEventHandlers   : function() {
    /* clicking the submit form */
    $('#send').bind('click',function(event){
        $('#loader').show();
        setTimeout('contact.ContactFormSubmit()',500);
    });
    /* remove messages when user wants to correct (focus on the input) */
    $('.inplaceError',$('#ContactForm')).bind('focus',function(){
        var $this       = $(this);
        var $error_elem = $this.next();
        if($error_elem.length)
            $error_elem.fadeOut(function(){$(this).empty()});
        $('#success_message').empty();  
    });
    /* user presses enter - submits form */
    $('#ContactForm input,#ContactForm textarea').keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
            $("#send").click();
            return false;  
        } 
        else  
            return true;  
    });
},
ContactFormSubmit   : function() {
    $.ajax({
           type     : 'POST',
           url      : 'php/contact.php?ts='+new Date().getTime(),
           dataType : 'json',
           data     : $('#ContactForm').serialize(),
           success  : function(data,textStatus){
                          //hide the ajax loader
                          $('#loader').hide();
                          if(data.result == '1'){
                              //show success message
                              $('#success_message').empty().html('Done!');
                              //reset all form fields
                              $('#ContactForm')[0].reset(); 
                              //envelope animation
                              $('#envelope').stop().show().animate({'marginTop':'-175px','marginLeft':'-246px','width':'492px','height':'350px','opacity':'0'},function(){
                                  $(this).css({'width':'246px','height':'175px','margin-left':'-123px','margin-top':'-88px','opacity':'1','display':'none'});
                              });
                          }
                          else if(data.result == '-1'){
                              for(var i=0; i < data.errors.length; ++i ){
                                  if(data.errors[i].value!='')
                                      $("#"+data.errors[i].name).next().html('<span>'+data.errors[i].value+'</span>').fadeIn();
                              }
                          }                       
                      },
           error    : function(data,textStatus){}
    });
}  
};
4

2 回答 2

0

棘手的问题...我自己也遇到过。问题不在编程方面;在 PHP 环境的版本上。

该代码在 PHP 5.4.12 和 Apache 2.4.4 上完美运行。并且在 PHP 5.3.27 和 Apahe 2.2.25 上没有将“结果”识别为属性,因为没有价值。完全相同的代码!奇怪,但真实...

所以......我不认为,在语言方面,任何人都可以帮助你/我们。干杯!

PS - 这是葡萄牙语的错误,由 IE 浏览器返回(在更高版本的环境中使用的相同!),一旦您提交联系表格:

'================================================== ======================

Agente do Utilizador:Mozilla/4.0(兼容;MSIE 7.0;Windows NT 6.0;Win64;x64;Trident/5.0;.NET CLR 2.0.50727;SLCC1;Media Center PC 5.0;.NET CLR 3.5.30729;.NET CLR 3.0 .30729;.NET4.0C;.NET4.0E) Carimbo de data/hora:2013 年 9 月 25 日星期三 16:45:12 UTC

Mensagem: Não é possível obter o valor da propriedade 'result': o objecto é nulo ou não definido Linha: 40 Caráct: 10 Código: 0 URL: .../jquery.contact.js '======== ==================================================== =============

于 2013-09-25T16:55:24.897 回答
0

此代码似乎源自http://tympanus.net/codrops/2010/03/12/php-mysql-contact-form-with-jquery/上的“PHP/MySQL Contact Form with jQuery”演示,效果很好对我来说“开箱即用”。

由于您没有提及配置,我猜您也没有编辑 config.php 以反映您自己的数据库:

define('DB_SERVER'          , 'localhost');
define('DB_USER'            , 'root');
define('DB_PASS'            , '');
define('DB_NAME'            , 'ContactForm');

或者,您可能忘记将 SEND_EMAIL 从 false 更改为 true

define('SEND_EMAIL', true);
于 2013-02-08T15:40:34.127 回答