Reputation: 179096
I was just reading another question about jQuery's synchronous ajax call, and I got to wondering:
What circumstances make a synchronous version of an ajax call beneficial/necessary?
Ideally I'd like an example, and why synchronous is better than standard ajax.
Upvotes: 17
Views: 4432
Reputation: 446
In sum, please do not use synchronous requests as @Brandon says: they are a cheap/easy/quick way to avoid making a callback. In addition, modern browsers show warnings if synchronous requests are made and we do not like that. Make your world asynchronous.
Upvotes: -1
Reputation: 5358
synchronous ajax is often used to retrieve a valued from the server which is required to further continue processing of client side code. in such case, the ajax call will block until the call returns with the desired value. example:
a javascript function needs to compute salary for an employee: step1 : get the employee id from the form step2 : make a sync server call passing the emp.id to get his salary/hour step3 : multiply salary rate by number of working hours
as you can see, total salary cannot be computed unless the server call is finished so this should be a sync function, although if using jquery, one could handle onSuccess to compute the salary asynchronously but processing will continue in this if you have a message box to display the salary, it will appear empty...
Upvotes: -2
Reputation: 630469
The only reasonable example I can think of (that can't be worked around another way) is making a call in window.onbeforeunload
, where you need it to be synchronous, or the page will move on and the request will never complete.
In this specific case using standard/asynchronous behavior, you're all but assured the request will die too early to have any impact, or ever contact the server.
I'm not saying I'm in favor of doing this, quite the opposite (as it negatively impacts the user's browsing speed). But...there's not much option here.
Upvotes: 21
Reputation: 4315
I would venture a guess that it'd be good in a scenario where you want to perform some ajax calls but you have one call that relies on the results of another call. If you perform them synchronously you can wait for the independent to finish before the dependent call fires.
Upvotes: -4