3

Is there a way to prevent ajax running async?

jQuery:

var returnValue = false;
        var appCount = 0;

        $.ajax({
            type: "GET",
            url: "getBookedAppointmentCountByDoctorAndDate.php",
            data: dataString,
            success: function (response){
                appCount = response;
                //alert(appCount);
                if(appCount >= 6){

                    returnValue = true;
                }
            }
        });
        return returnValue;

I have an if statement in my code that checks the return value of this function. Because Ajax runs async, the if statement is continuing before the return value is set. Any ideas or suggestions of other methods to use to return php value?

if (blah($(this)) === true) {
                    alert("blah");
                } else { ...
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
japes Sophey
  • 487
  • 3
  • 8
  • 26
  • 1
    There is a way, but the real answer here is, **you should never do it** ! – adeneo Dec 09 '15 at 22:24
  • 1
    In your request, you must do async: false http://api.jquery.com/jQuery.ajax/ – Zoran Pandovski Dec 09 '15 at 22:24
  • 1
    [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – adeneo Dec 09 '15 at 22:24
  • You never never should use sync methods on browser because freeze the main thread. To "return" a valud when the ajax call end you should use a callback (or, more advance, return a promise). – Jose Mato Dec 09 '15 at 22:24

2 Answers2

2

Add parameter async: false to ajax parameters http://api.jquery.com/jquery.ajax/, browser will be inactive while ajax request, so it is not good decision.

Better move if statement to ajax success function, or make function with if statement and call it in success function.

Max P.
  • 5,579
  • 2
  • 13
  • 32
1

You are using this snippet inside a function, right? Since you have a return statement, I'm guessing so.

You can not return the value that is going to be determined in an async task. What you could do is to pass a callback function to this function and when the value is determined, pass the value to that function and call it.

function myFunc(callback) {

    var returnValue = false;
    var appCount = 0;

    $.ajax({
        type: "GET",
        url: "getBookedAppointmentCountByDoctorAndDate.php",
        data: dataString,
        success: function (response){
            appCount = response;
            //alert(appCount);
            if(appCount >= 6){
                returnValue = true;
            }
            callback(returnValue);
        }
    });
}



myFunc(function (value) {
    console.log(value);
    // do what ever you want with `value`
})

Another approach is to use Promise. In case you want to use jQuery's promises, here is the documentations

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52