使用php + mysql进行奇怪的AJAX行为。部分工作/部分不?

时间:2011-09-16 18:42:23

标签: php javascript jquery mysql ajax

我正在尝试在我的表单中添加一些AJAX,但是我对我已经有一段时间的问题非常困惑。

我有两个PHP页面,dashboard.php,process-register.php。

用户可以登录他们的仪表板并将产品的电子邮件许可证发送到他们选择的电子邮件地址。这是在dashboard.php页面上。提交后,将调用process-register并将新用户插入到数据库中,并通过电子邮件向他们发送登录详细信息。

奇怪的是,当我将电子邮件字段留空并单击提交时,它总是返回process-register.php页面上指定的错误,但是,当我输入电子邮件地址并单击提交时,它只刷新页面什么都不做奇怪的是,在奇怪的场合,它确实有效并且创建了一个新用户。这只是我说的1/5次。

下面的JavaScript:

  $("#form-submit").click(function() { 
        $.ajax({
        cache: true,
        type: 'POST',
        url: 'process-register.php',
        data: $("#form-register").serialize(),
        success: function(response) {
            $("#output-div").html(response);
        }
        });
    }); 

Dashboard.php

<?php
    include("config.php");
       if(empty($_SESSION['email']))
        {
        echo "Please login...redirecting";
        echo '<meta HTTP-EQUIV="REFRESH" content="2; url=http://example.com">';
        }
        else
        {
        ?>
    <?php include_once 'header.php'; ?>
    <div id ="terms-content-wrapper">
        <div id="content" class="wrap">
        <div id="register">
                        <form id="form-register" class="testform" method="POST" form action="" >
                    <h4>Send License</h4>
                    <?php 
        $qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
        while($row = mysql_fetch_array($qry)) {
            if ($row['codes_remaining'] ==1 ) 
            {
            echo "You have ".$row['codes_remaining'].' code remaining';
            }
            else {
        echo "You have ".$row['codes_remaining'].' codes remaining';
        }
        }
    ?>
                    <p>
                    Enter the e-mail address of the person you would like to send a license to.
                    </p>
                    <p>
                        <label for="email">Email Address:</label>
                        <input id="email" class="required email" value="" type="text" name="email">
                    </p>
                    <br>
                        <p class="buttons">
                            <input name="submit" type="submit" id="form-submit"/>
                    </form>
                </div>
            <div id="output-div"></div>
        </div>
    </div>
    <p></p> <!--content-wrapper div -->    
    <?php include_once 'footer.php'; ?> 
    <?php
        }
    ?>

过程-register.php

<?php
    include("config.php");
    $username = mysql_real_escape_string( stripslashes($_POST['email']));
    //password emailed to user
    function createPassword($length) {
    $chars = "234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $i = 0;
    $password = "";
    while ($i <= $length) {
        $password .= $chars{mt_rand(0,strlen($chars))};
        $i++;
    }
    return $password;
}

$password = createPassword(8);

function genRandomString() {
    $length = 20;
    $characters = "23456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $string = "";    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}
$validation = genRandomString();

    if(($username != "") && ($password != ""))
    {
    //all fields have something in
    $sql = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
   while($row = mysql_fetch_array($sql)) 
    {
    if($row['codes_remaining'] > 0)
    {
    //create a new user
    mysql_query("INSERT INTO users (email, password, verification_code) VALUES('". mysql_escape_string($username) ."', '".md5($password)."', '". mysql_escape_string($validation) ."') ") or die(mysql_error()); 
    //email them the details.
        $to      = $username;
        $subject = 'You lucky devil';
        $message = '

        Some kind fellow / lady has bought you something

        Login to: http://example.com/login

        Your account information
        -------------------------
        Email: '.$username.'
        Password: '.$password.'
        -------------------------

        If you have any problems, please contact us and we will sort it out ASAP.

        Thanks again;

        $headers = 'From:support@example.com' . "\r\n";

        mail($to, $subject, $message, $headers);

        mysql_query("UPDATE users SET codes_remaining = codes_remaining-1 WHERE email= '".$_SESSION['email']."'");

        echo "You have create a new user";
            }
        else
            {
            echo "Error: You do not have any licenses left. Please purchase some more.";
            }
        }
    }
    else
    {
    echo "Error: Please fill in all the fields.";
    }
?>

正如我所说,当我输入一封电子邮件时,它只能在20%的时间内工作并且仍然感觉迟钝,但是当我把它留空并提交时,我总是得到错误代码返回而页面没有刷新。

非常感谢有关此事的任何帮助, 谢谢, Lordsnoutimus

1 个答案:

答案 0 :(得分:5)

绑定表单的提交事件,但不会停止表单的正常提交。 添加返回false;在$(“#form-submit”)的末尾。单击(function(){

或者event.preventDefault(),如下所示:

  $("#form-submit").click(function(e) { 
        e.preventDefault();
        $.ajax({
        cache: true,
        type: 'POST',
        url: 'process-register.php',
        data: $("#form-register").serialize(),
        success: function(response) {
            $("#output-div").html(response);
        }
        });
        // return false; would do the same.
    }); 

在您的情况下,当您单击按钮时,表单将照常提交(非AJAX方式),如果进程足够慢,则某些绑定代码将有时间运行。 ..所以一段时间提交过程足够慢,以便准备AJAX请求&amp;已发送,但大多数时候您已经离开页面才会发生。