user1697061
user1697061

Reputation: 265

Ajax call too slow ? Javascript and PHP

I am setting up a registration form. This form has 7 fields that are being tested for validation. 2 of them have a special validation; I have an Ajax call to a PHP class where I send an email_string to this class, testing, if such an email already exists in my database (evading duplicates).

params = {};
params['source'] = 'checkEMail';
params['email']  = email
$.ajax({
    type: 'POST',
    url : 'some_class.php',
    data : params,
    success: function(msg)
    {
        if(msg > 0) /* email exists */
            is_error = true;
    }
});

And in my PHP Class I got something like this:

$final = mysql_fetch_assoc(foo);
echo ($final) ? 1 : 0;

I was testing the data and in fact - I get '1' if the email exists and '0' if it does not.

Funny thing is, that this snippet works fine AS LONG AS there are other errors in this form - like an empty username. The "is_error" is a boolean that is set to false at the beginning of the script and if one validation fails, it gets true. Then, finally, I got this:

if(is_error)
{
    error.show();
    error.empty().append('some html foo');
}
else
{
    $('form').submit();
    error.empty().hide();
}

So how can it be that I the form will be send although is_error is set to true? Only reason I could think of is that the form is being send before the "is_error" is being testet - but the send of the form is at the very bottom of the script.

Oh and I am calling it this way:

<script type="text/javascript">
            $("#reg_submit").click(function(event) {
                event.preventDefault(); 
                checkReg();
            });
</script>

Upvotes: 0

Views: 1623

Answers (2)

Andreyco
Andreyco

Reputation: 22872

Maybe it is caused by different output types that you are trying to match...

First, change your PHP output to

echo json_encode($final ? true : false);

Then, to work with JSON, I would add this line to ajax calling method, to be sure...

$.ajax({
    type: 'POST',
    dataType:'json',
    ...
    success: function(msg)
    {
        if(msg!==true){
            is_error = true;
        }
    }
});

Upvotes: 1

aleation
aleation

Reputation: 4834

instead of having the if(is_error){ part at the end of the script, I would suggest you to do it in the ajax request completion to avoid race conditions:

$.ajax({
    type: 'POST',
    url: 'some_class.php',
    data: params,
    success: function(msg) {
        if (msg > 0) /* email exists */
        is_error = true;
    },
    complete: function() {
        if (is_error) {
            error.show();
            error.empty().append('some html foo');
        } else {
            $('form').submit();
            error.empty().hide();
        }
    }
 });

Upvotes: 1

Related Questions