How to wait for JQUERY AJAX response before choosing condition How to wait for JQUERY AJAX response before choosing condition ajax ajax

How to wait for JQUERY AJAX response before choosing condition


Try setting async to false: (See edit below)

$.ajax({    type: "POST",    async: false,    url: "/webservice/user.asmx/CheckForm",    data: "{'type':'" + var_type + "', 'value':'" + var_value + "'}",    contentType: "application/json; charset=utf-8",    dataType: "json",    error: function (XMLHttpRequest, textStatus, errorThrown) { },    success: function (data) {        var obj = data.d;    }});

This will make the AJAX call blocking so the browser will wait for it to finish before continuing. Of course, I'm still not sure how that relates back to the boolean being checked in the parent conditional. Maybe there's code you're not showing us...


Edit: :::sigh::: I was young and foolish when I posted this answer, and in fact had forgotten all about it. I'm keeping the above information unchanged for historical purposes (since it seems to have helped some people, or at least they think it has), but understand that this is not a correct approach.

Making asynchronous calls synchronous and blocking execution is in every way incorrect. Don't do it. Instead, structure the logic to respond to the asynchronous operations. In the case of this question, calls to console.log() should be happening in the success (or error) handler of the AJAX call, not in the code after the invocation of that call.


You have to do this in the callback from the ajax call -- like this:

$.ajax({    type: "POST",    url: "/webservice/user.asmx/CheckForm",    data: "{'type':'" + var_type + "', 'value':'" + var_value + "'}",    contentType: "application/json; charset=utf-8",    dataType: "json",    error: function (XMLHttpRequest, textStatus, errorThrown) {      console.log('error');    },    success: function (data) {      console.log('here');    }});

Using AJAX requires non-linear programming -- callbacks abound.

You could set the option in the ajax call that makes it not async (ie jQuery will wait for it to finish) but this will make your application/web site not perform as well.


Yeah, you put the conditional inside the success function.

 success: function (data) { if (...) { } else { }         var obj = data.d;    }