How to make JQuery-AJAX request synchronous

Kanishk Dudeja picture Kanishk Dudeja · Dec 20, 2012 · Viewed 131.3k times · Source

How do i make an ajax request synchronous?

I have a form which needs to be submitted. But it needs to be submitted only when the user enters the correct password.

Here is the form code:

<form name="form" action="insert.php" method="post" onSubmit="return ajaxSubmit(this);" >

And the jquery code for sending and checking password is this:

var ajaxSubmit = function(formE1) {

    var password = $.trim($('#employee_password').val());

    $.ajax({
        type: "POST",
        async: "false",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            if(arr == "Successful") {
                return true;
            } else {
                return false;
            }
        }
    });
}

However the form always submits, regardless of the value returned by the ajax request. I have checked everything else. The value of arr is coming out to be 'successful' when correct password is entered and works correctly vice versa too.

How do i make this request synchronous? as far as i can debug, the request is asynchronous so the form gets submitted before the request gets completed.

Code for checkpass.php

<?php 
require("includes/apptop.php");
require("classes/class_employee.php");
require("classes/class_employee_attendance.php");

$employee_password=$_POST['password']; 

$m=new employee();
$m->setbyid_employee(1);
$arr=$m->editdisplay_employee();

if($arr['employee_password'] == $employee_password)
{
$res="Successful";  
}
else
{
$res="Password not match";  
}

echo $res;
?>

Update: The solution has been found.

As pointed by Olaf Dietshche: The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

So, I set a variable to 1 inside success function upon successful. And checked its value out of success function, if it was 1 outside the success function, then I wrote return true ... else return false. And that worked.

Updated working code:

var ajaxsubmit=function(forme1) {
    var password = $.trim($('#employee_password').val());
    var test="0";

    $.ajax({
        type: "POST",
        url: "checkpass.php",
        async: false,
        data: "password="+password,
        success: function(html) {
            if(html == "Successful") {
                test="1";
            } else {
                alert("Password incorrect. Please enter correct password.");
                test="0";
            }
        }
    });

    if(test=="1") {
        return true;
    } else if(test=="0") {
        return false;
    }
}

Answer

Olaf Dietsche picture Olaf Dietsche · Dec 20, 2012

From jQuery.ajax()

async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

So in your request, you must do async: false instead of async: "false".

Update:

The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

Something along these lines should work

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}