When is it appropriate to use synchronous ajax? - javascript

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.

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.

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.

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...

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.

Related

Requesting all results (synchronously) from cursor paginated APIs

I need to collect all pages from an API that uses cursor-based pagination. Each call returns (in addition to a page of data) a boolean 'hasNext' and a key 'after'. If 'hasNext' is true, the next request passes 'after' to indicate where the next result should start.
Since each call is dependent on the result of the previous one, it seems this must be done synchronously. I can probably use XMLHttpRequest to make synchronous calls, but I often see comments that say synchronous requests are being deprecated and fetch is for asynchronous requests only.
Any suggestions on how to handle synchronous requests (where each request is dependent on the result of the previous one and the results need to be in order)?
I've seen several methods for handling paginated APIs, but they all seem to apply to offset pagination.

AJAX: Asyncronous calls in Javascript to Java

I currently have a few basic question with asynchronous calls in JS.
I have searched and found a similar question posted in the past here:
Parallel Ajax Calls in Javascript/jQuery
But I still have some doubts about asynchronous calls.
Let´s say that I make it asynchronous using a jQuery when to join both flows when both AJAX calls are finished. What would happen if one of the AJAX calls fail?
Some of the calls that I need to make should be asynchronous only in some cases. Is it a good practice to make the type of call (asynchronous true or false) variable? Or doesn't it really matter to have an asynchronous true call when there is only one JS flow?
If I need to do a few database calls with my asynchronous methods (different tables). Could I have a conflict if i make two database calls at the same time because make my AJAX asynchronous? I am quite new to asynchronous calls. (SQL database) (Spring Boot Java 8)
The basic flow would be something like this:
Ths answer is a compilation of everything told in the comments, not my own.
You handle it in your code.
Synchronous calls are deprecated, so never make a synchronous ajax call - the first A in AJAX actually stands for Asynchronous, so a Synchronous AJAX request makes no sense anyway (though of course it is a thing)
It is the same in Java as most other systems: the backend may process your calls in a different order or even truly in parallel (think a cluster, one call is processed from one node, the other call fro another node). So it depends on your semantics: if one depends on the outcome of the other, then you should make sure they are only called sequentially. If they both contribute independently to the final outcome, then you have to make sure to revert the effects of the one, if the other fails. There are many ways to do that - and maybe it should be a responsibility of the backend.

How can I have some portions of Ajax occur synchronously, while front end logic occurs asynchronously?

I have a site I'd like to check through several environments for login credentials, but in the mean time, display a loading gif.
Trouble is, if I make the ajax synchronous or,
async: false,
then the rest of the page pauses until the credentials are checked.
I tried switching the ajax calls back to asynchronous, it will prematurely display a false negative error that the user isn't logged in, since it hasn't finished checking all environments.
I also tried a kind of band-aid solution with
setTimeout(loginCheckFunction, 600)
But that's arbitrary timing, and if the user has a slow connection, the false error will persist.
Any ideas on how to make some portions run without waiting for the synchronous Ajax to finish?
Thanks!
edit:
I think my issue is pretty much inadvertently solved by this question:
How to display 'Loading' when making a 'synchronous' AJAX call in pure JavaScript?
edit 2:
I skirted the issue by using the top answer to the above question. I gave a very small setTimeout function to the beginning of parent function calling the synchronous ajax-based login checks, during which time the 'loading' gif can be launched, and viewed simultaneously while ajax runs.
Per the answer given though, in the strictest sense, it isn't running simultaneously, the browser just provides that illusion.
For future persons maybe running into similar issue, I transitioned from setTimeout being applied on the child function, to setTimeout being applied one level up on its the parent function.
Have you tried do one ajax call after another ajax call ends?
First you show your loading screen and do the ajax calls one after another ends. In the last call you hide your loading. In this way you parallelize all the ajax call, validating each pass.
You can use the Ajax Queue plugin

How can I track AJAX calls and determine whether calling the callback function is no longer necessary?

I have a web application that is growing more complex. It makes heavy use of JavaScript based HTML generation and AJAX calls, and herein lies my problem:
Since I can't know how long an ajax call might take getting back to client side, I don't know when the callback gets actually executed. The user might have at that point navigated away from the element that originally caused the AJAX event, in which case this callback can cause some havoc. Is there a way to "expire" old callbacks ?
Are there any libraries that would offer that functionality? (I am using jQuery now but am not 100% familiar with it).
Thanks,
You might want to look into Ajax Queue Manager. There are params you can set to abort old requests before sending a new one. I think that might be what your looking for.
Well, the simple answer is to check for the proper state of your app within your callback functions, before they do whatever it is they are doing that causes problems. For example, you could make sure that certain elements are still being hovered over.

pause current ajax call , carry out a new one , after carrying out , continue the default ajax call

i'm not sure this is possible.
I have two ajax calls executed during a button click event.
first ajax call is to add data to database using jquery ajax post .
the second one is to add another set of data to database too via jquery ajax post too
The first one will execute first then the second one. i have set a timer to the second call(windowstimeout) to create a time interval between both execution to test if i can pause the first ajax call.
You will be asking me why i don't want to combine both calls. i have the reasons to do, and i want to know is it really possible to pause an ajax call. I have search around the net , all i found is the ajaxstop(jQuery) but it don't really pause it , it stops the ajax call.
SO anyone have any idea to do so? Thanks.
Why do you want to pause it? You can't, but why would you want to? Just let them both run, or don't trigger the first call till the second is done.
No, you cannot pause Ajax calls - they are just instances of the normal HTTP request/response cycle and behave as such. If the server-side operations resulting from the second call depend on the results of the first one, then why don't you just chain the calls and trigger the second one in the first's success callback handler?
You cannot do that.
You should really ask yourself if the design of your data exchange protocol is correct.
Pausing a request (whatever the communication protocol is, AJAX or any other) should not work since you cannot know if there are other requests and what they do.
So ask yourself the questions: what is my exact need ? what are the other ways to do that ?

Categories