简体   繁体   English

php + mysql的异常AJAX行为。 部分工作/部分不工作?

[英]Bizarre AJAX behavior with php + mysql. Part working / part not?

I'm trying to add some AJAX to my forms, however I am extremely confused with an issue I have been having for a while now. 我正在尝试向表单中添加一些AJAX,但是我对已经存在一段时间的问题感到非常困惑。

I have two PHP pages, dashboard.php, process-register.php. 我有两个PHP页面,dashboard.php,process-register.php。

A user can log into their dashboard and email licenses for a product to an email address of their choosing. 用户可以登录其仪表板并通过电子邮件将产品许可发送到他们选择的电子邮件地址。 This is on the dashboard.php page. 这是在dashboard.php页面上。 Once submitted, process-register is called and inserts the new user into the db as well as emailing them their login details. 提交后,将调用process-register并将新用户插入数据库,并通过电子邮件将其登录详细信息发送给他们。

The strange thing is, When I leave the email field blank and click submit it always returns the error specified on the process-register.php page, however, when I enter in an email address and click submit it just refreshes the page and does nothing. 奇怪的是,当我将电子邮件字段保留为空白并单击“提交”时,它总是返回在process-register.php页面上指定的错误,但是,当我输入电子邮件地址并单击“提交”时,它只会刷新页面而不执行任何操作。 The strange thing is, on the odd occasion, it does work and a new user is created. 奇怪的是,在奇怪的情况下,它确实起作用并且创建了一个新用户。 This is only every 1/5 times i'd say. 我只说每1/5次。

JavaScript below: 以下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 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
        }
    ?>

process-register.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.";
    }
?>

As i've said, when I enter an email, it only works about 20% of the time and still feels sluggish, however when I leave it blank and submit, i always get the error code returned and the page doesn't refresh. 就像我说过的那样,当我输入电子邮件时,它只能在20%的时间内工作并且仍然感觉呆滞,但是当我将其保留为空白并提交时,我总是会得到返回的错误代码,并且页面不会刷新。

Would really appreciated any help on this matter, Thanks, Lordsnoutimus 非常感谢您在此问题上的任何帮助,谢谢,Lordsnoutimus

You bind the submit event of the form, but you don't stop the normal submit of the form. 您绑定表单的Submit事件,但是您不停止表单的正常提交。 Add a return false; 添加return false; at the end of your $("#form-submit").click(function() { 在$(“#form-submit”)。click(function(){

Or a event.preventDefault(), like this: 或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.
    }); 

In your case, what happen is that when you click your button, the form is submitted as usual (non-AJAX way), and if the process is slow enough, some of the binded code will have the time to run... so some time the submit process is slow enough to allow the AJAX request to be prepared & sent, but most of the time you've left the page before it can happen. 在您的情况下,发生的事情是,当您单击按钮时,表单照常提交(非AJAX方式),并且如果过程足够慢,则某些绑定的代码将有时间运行...所以提交过程有时会很慢,以至于无法准备和发送AJAX请求,但是大多数情况下,您在离开页面之前就无法进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM