Reputation: 2588
In the below code fun1() & fun2() are executed asynchronously, but they are dependent on the success of the json call placed above them.
$.getJSON("../../CreateCustomer/SaveRoleInSession/" + data.SelectedRole, null, function (data) {});
Fun1();
Fun2();
Can I place those function calls inside the braces to make it synchronous?
that is :
$.getJSON("../../CreateCustomer/SaveRoleInSession/" + data.SelectedRole, null, function (data)
{
Fun1();
Fun2();
});
Upvotes: 1
Views: 1709
Reputation: 81
That won't exactly make it synchronous (the call still doesn't block), but it will result in your methods getting called as part of the callback after the response is returned, which may work just fine for your circumstances.
I'm learning jquery ajax myself and best I can tell is that you need to use the ajax() method with the async option set to false for true synchro behaviour.
The example given in the api browser is:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
I'm trying to issue a synchronous request myself inside of a client side validation method in ASP.NET and one downside to this approach when using a JSON service is that you are left to do the JSON parsing/deserialization yourself, whereas in an async request the parsed data is passed to your success callback as an object. I came across your question trying to find the preferred method to do the parsing of the responseText. The api browser I was looking at doesn't seem to contain the parseJSON method, but there is one, so I'll go with that vs. Eval().
It's also worth noting that before noticing their synchronous example, I attempted to set the async option to false and have my callback method write to a global variable then reference that var in the lines below the aync call and not reference the XMLHttpRequest.responseText property, but that was ineffective. It seemed that the lines following the ajax call were not getting executed when done that way. YMMV.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.parseJSON/
Upvotes: 3