[jquery] How to make JQuery-AJAX request synchronous

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;
    }
}

This question is related to jquery ajax synchronous

The answer is


It's as simple as the one below, and works like a charm.

My solution perfectly answers your question: How to make JQuery-AJAX request synchronous

Set ajax to synchronous before the ajax call, and then reset it after your ajax call:

$.ajaxSetup({async: false});

$ajax({ajax call....});

$.ajaxSetup({async: true});

In your case it would look like this:

$.ajaxSetup({async: false});

$.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;
            }
        }
    });


$.ajaxSetup({async: true});

I hope it helps :)


try this

the solution is, work with callbacks like this

$(function() {

    var jForm = $('form[name=form]');
    var jPWField = $('#employee_password');

    function getCheckedState() {
        return jForm.data('checked_state');
    };

    function setChecked(s) {
        jForm.data('checked_state', s);
    };


    jPWField.change(function() {
        //reset checked thing
        setChecked(null);
    }).trigger('change');

    jForm.submit(function(){
        switch(getCheckedState()) {
            case 'valid':
                return true;
            case 'invalid':
                //invalid, don submit
                return false;
            default:
                //make your check
                var password = $.trim(jPWField.val());

                $.ajax({
                    type: "POST",
                    async: "false",
                    url: "checkpass.php",
                    data: {
                        "password": $.trim(jPWField.val);
                    }
                    success: function(html) {
                        var arr=$.parseJSON(html);
                        setChecked(arr == "Successful" ? 'valid': 'invalid');
                        //submit again
                        jForm.submit();
                    }
                    });
                return false;
        }

    });
 });

Can you try 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")
                    { 
                         **$("form[name='form']").submit();**
                        return true;
                    }
                    else
                    {    return false;
                    }
                }
            });
              **return false;**
        }

I added dataType as json and made the response as json:

PHP

echo json_encode(array('success'=>$res)); //send the response as json **use this instead of echo $res in your php file**

JavaScript

  var ajaxSubmit = function(formE1) {

        var password = $.trim($('#employee_password').val());    
        $.ajax({
            type: "POST",
            async: "false",
            url: "checkpass.php",
            data: "password="+password,
            dataType:'json',  //added this so the response is in json
            success: function(result) {
                var arr=result.success;
                if(arr == "Successful")
                {    return true;
                }
                else
                {    return false;
                }
            }
        });

  return false
}

The below is a working example. Add async:false.

const response = $.ajax({
                    type:"POST",
                    dataType:"json",
                    async:false, 
                    url:"your-url",
                    data:{"data":"data"}                        
                });                   
 console.log("response: ", response);

Instead of adding onSubmit event, you can prevent the default action for submit button.

So, in the following html:

<form name="form" action="insert.php" method="post">
    <input type='submit' />
</form>?

first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

$('input[type=submit]').click(function(e) {
    e.preventDefault(); //prevent form submit when button is clicked

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

     $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            var $form = $('form');
            if(arr == "Successful")
            {    
                $form.submit(); //submit the form if the password is correct
            }
        }
    });
});????????????????????????????????

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to synchronous

How to wrap async function calls into a sync function in Node.js or Javascript? What is the difference between synchronous and asynchronous programming (in node.js) How to make JQuery-AJAX request synchronous Simplest way to wait some asynchronous tasks complete, in Javascript? jQuery: Performing synchronous AJAX requests document.createElement("script") synchronously JavaScript: Global variables after Ajax requests asynchronous vs non-blocking How to force Sequential Javascript Execution? Asynchronous vs synchronous execution, what does it really mean?