php到mySQL提交按钮工作,后端不要

时间:2012-07-14 00:21:21

标签: php mysql ajax forms submit

所以我的问题是页面的美观效果,直到你点击提交按钮的位置(它的工作原理是因为有一个加载图像设置为在通过jquery.contact单击按钮后出现。 JS)。但是,它会在加载图像处停留,并且不会返回提示已成功提交的消息,也不会返回到我的数据库中,也不会发送确认电子邮件(忽略)。

我想知道出了什么问题以及我如何解决它,如果可能的话,我可以快速完成这项任务,以便快速完成这项工作?

这是脚本:

的index.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>

Contact.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;
}
};

db.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){}
    });
}  
};

2 个答案:

答案 0 :(得分:0)

此代码似乎源自http://tympanus.net/codrops/2010/03/12/php-mysql-contact-form-with-jquery/的“PHP / MySQL联系表格与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);

答案 1 :(得分:0)

很难......我自己也有过。 问题不在于编程方面;是关于PHP environement的版本。

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

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

PS - 一旦你提交了联系表格,就会出现IE浏览器返回的葡萄牙语错误(在更高版本的environement中使用的错误!),

“============================================== ========================

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:Wed,25 Sep 2013 16:45:12 UTC

Mensagem:Nãoépossívelobtero valor da propriedade'endult':oobjectoénuloounãodefinido 林哈:40 Caráct:10 Código:0 网址:... / jquery.contact.js “================================================= =====================