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

jcr*_*son 2 javascript php mysql ajax jquery

我正在尝试在我的表单中添加一些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);
        }
        });
    }); 
Run Code Online (Sandbox Code Playgroud)

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
        }
    ?>
Run Code Online (Sandbox Code Playgroud)

流程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.";
    }
?>
Run Code Online (Sandbox Code Playgroud)

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

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

FMa*_*008 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.
    }); 
Run Code Online (Sandbox Code Playgroud)

在您的情况下,当您单击按钮时,表单将照常提交(非AJAX方式),如果进程足够慢,则某些绑定代码将有时间运行...所以有时候提交过程的速度很慢,无法准备和发送AJAX请求,但大部分时间你都会在页面发生之前离开页面.

  • Bingo,它在5中的1次运行是因为AJAX在浏览器完成表单提交操作之前完成. (2认同)