开发者

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.

I have two PHP pages, 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. Once submitted, process-register is called and inserts the new user into the db as well as emailing them their login details.

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

JavaScript below:

  $("#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
        }
    ?>

process-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.

Would really appreciated any help on this matter, Thanks, Lordsnoutimus


You bind the submit event of the form, but you don't stop the normal submit of the form. Add a return false; at the end of your $("#form-submit").click(function() {

Or a event.preventDefault(), like this:

  $("#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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜