Ajax makes what type of calls? - javascript

hi I want to ask about AJAX ,either AJAX makes Synchronous or Asynchronous calls to the Server.As from its name It is ASYNCHRONOUS JS & XML ,but when it comes to sending request to server,it is synchronous or Asynchronous?Help will be Appreciated

It's a loosely defined buzzword. JS can make both. Synchronous calls are locking and should almost always be avoided though.

I think it would help you if you had a definition of what synchronous and asynchronous mean in this context.
A synchronous call blocks the execution of the Javascript thread that executed it. This means if you have the following code:
console.log('Before');
xhr.send();
console.log('After');
You will not see the After message until the request has completed and the server has returned data.
An asynchronous call does not block the execution of the Javascript thread that executed it. This means that, for the same code block above, the After message fires immediately, and does not wait for the request to finish. Because the execution of the code continues in an asynchronous call, you need to use a callback to handle the result. This is what the onreadystatechange() event/method is for.
You can choose which type of call is made, synchronous or asynchronous, when you call the open() method of the XmlHttpRequest object. By passing true to the third argument, the request is asynchronous, if you pass false it is synchronous.

It can actually be both, sync and async.

indeed, it can be both synchronuous and asynchronuous. When the call is made synchronuously, your code doesn't continue until the request has been completed and a response has been received. This is not what you want in many cases, since this freezes all javascript driven parts of your website.

The Request is asynchronous because the Browser must not wait for the response of the request. So that means on the one hand you can have a synchronous for example you send your request and show a wait-screen but on the other hand you can send your request to the server and the server responds at any time. Your browser can process the response but the user can work without any influences with you page.

Related

is $ajax() call with a successcallback really asynchronous

I am kind of confused right now. I have the following asynchronous ajax call where I am passing a successcallback.
ajax('PUT', 'some URL', successCallback, data);
I observe that this callback is called when the request completes so I fail to understand how this call is asynchronous if it waits for the call to complete.
If I do not pass the successcallback to ajax and return the callback from the function I can observe asynchronous behavior as expected
ajax('PUT', 'some URL', undefined, data);
return successcallback();
With above change I actually observe the ajax call executing asynchronously and my page can proceed but if the page redirects to some other link the the request gets cancelled. So the only option that works is passing in succesCallback for ajax but it seems to be syncronous rather than asynchronous
I think you have your terminology backwards. "Asynchronous" in this context means "runs at some future point in time and doesn't block immediate execution of code". "Synchronous" is a blocking call, one that will halt execution until it's complete.
The callback there is intended to be executed when the request is complete, which is by definition "asynchronous". Your alternate version runs the success callback regardless, and it does that long before the AJAX call is initiated as well as not knowing if it will succeed.
You need to do asynchronous calls otherwise the JavaScript code and engine are completely jammed waiting for a response. This used to be acceptable when this is a separate process with no other responsibilities, but it's a disaster in a web application where your code likely has other things it has to respond to.

How to make sure all ajax calls got executed successfully ( not completed)

I know this question has been asked multiple times before as how to execute function when all AJAX call has been completed. We can user jquery.stop() in this case.
But my requirement is different. I want to show confirm banner when all ajax call have been executed successfully. For different pages , I have multiple AJAX calls. I do not want to put any condition on each AJAX call success method.
Can any one suggest if there is any global way.
Thanks in advance.
your are searching for global event handlers:
https://api.jquery.com/category/ajax/global-ajax-event-handlers/
http://api.jquery.com/ajaxcomplete/
anytime when you call an ajax request you "see" it via .ajaxSend() and handle response via .ajaxComplete()

Google Chrome scroll freezing while appending ajax content on a page

I have a problem with chrome scrollbar,on Mozilla there is no such a problem.
I have couple of synchronous ajax requests and then some info appending on the page,they need about 2 secs to load.During this time the scrollbar freezes and is not usable,when the ajax end the scroll works fine.
Javascript is completely single-threaded.
If you make multiple AJAX calls, you will receive each response as
soon as the server sends it; the order depends on the amount of time
that it takes the server to send each reply.
If your code is still running when the server replies, the reply will
only be processed after your code finishes.
You should try to load all of the data in a single request.
Source: SLaks
I might hit a wall here, in other programming languages you can start a new thread for connections/things like that, if you run multiply threads (kinda like layers) your interface stays the way it is/was.
When you use synchronous AJAX the page stops until ajax finish, so if you want the page not stop, must be asynchronous AJAX call.
You can see more here:
Documentation AJAX W3Schools
The problem you are describing is not browser behavior problem.
When you make an synchronous request it means that the the code pending for the response.
Since javascript is a single threaded language (lets ignore web-workers for now),
also the UI processing/manipulation is pending,
and this is why the browser or scroll-bar "stuck".
The reason it works on Firefox is that synchronous calls are deprecated (btw because of the "stuck" behavior), and what you are actually doing there is asynchronous request;
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

state of XMLHttpRequest Object in jquery AJAX

In traditional javascript AJAX, we know if readystate is:
0 - The request is not initialized
1- The request has been set up
2 - The request has been sent
3 - The request is in process
4 - The request is complete.
When it comes to jQuery AJAX, we have:
complete property where we code what should happen after completion
success property where we code what should happen if the ajax request succeeds and
error property where we code what should happen if ajax request fails.
All of the above properties lets us code to do something after completion of ajax request. Where can I specify some code to execute something during processing(when readyState is 3) in Jquery Ajax??
As my AJAX script takes too long time to execute, which means, I will not attain 'complete' stage quickly. This seems like nothing is happening to the user. I wanted to initiate another ajax script at processing stage which gets information from server meanwhile and shows the user what has been done so far. Is it possible at all in Javascript? I know there is no multi-threading in Javascript.
I think I made my self clear. But, Please let me know if anything is not making any sense.
I handle this by initiating the first long running request, returning to the user immediately and allowing the process to fork server side for the extended processing.
The initial return ajax call to the user sets them up to 'watch' that process via a flag against the object ( I store them against the object in the database, but you could for instance watch file sizes or other stuff )
Subsequent ajax calls occur in a loop, each one returning setTimeout for the next call, and report on changes to that flag so the progress of the long running process is then visible. Completion of the long running process prompts NOT sending another setTimeout() and showing the overall results.
If your process is not that intensive, a simple spinner would probably do the job and no work for your server process. I usually handle that having $.ajax flip the visibility of a 'spinner' icon that's preloaded on my pages in the same spot for all.
According to jQuery's Ajax documention, they do not expose the readystate change event:
No onreadystatechange mechanism is provided, however, since success,
error, complete and statusCode cover all conceivable requirements.
It would be possible to show a loading image after the initial Ajax request is kicked off (and before getting any "complete" or "success" events, and then start polling a different URL via ajax which will give you the status of the first request, assuming your server can show progress of the long process before it completes.

JavaScript flow or execution

If I have a JS function as follows;
function testFn()
{
x.ajaxMethod(param1,JScallBackFunction); //Please do not worry about the syntax..this just indicates an external method call
alert("Line after ajaxMethod");
}
The ajaxMethod(), lets say is some kind of method defined in an external Java file (so it can be through DWR or anything) which returns some data...Point is it takes some time to execute this line of code...
Now my question is when will the alert on next line get fired (i.e. alert("Line after ajaxMethod");)
Will it wait for these 2 things to complete (ajaxMethod execution as well as JScallBackFunction)
OR
It will be fired immediately without waiting for any of the above 2 things to complete ?
Also if you could guide in general about the JavaScript method flow execution, that will be great.
It depends. Ajax calls are usually asynchronous which means the execution of code will not be paused until the asynchronous function returns. Therefore the alert will be executed immediately.
Asynchronous functions in javascript are usually to do with Ajax and loading something from a remote server. If you do wish to force JavaScript to wait while loading that content then you can set a flag for the XMLHTTPRequest object.
this is a good question to read: When is JavaScript synchronous?
it will fire immediately after the ajax call. if you want it to wait put it in the callback function.
edit: a method that defines a callback is essentially this:
function(param1, callback) {
// do stuff
callback(); // execute callback
}
First, when you say
The ajaxMethod(), lets say is some
kind of method defined in an external
Java file
I suppose you really mean external JavaScript file.
When you send an Ajax request, you ask the browser to send a request to the server for you.
This request on the server may take sometime and you don't want to "wait" on it. (This is the whole idea of Async requests - stuff in the background).
So you tell the browser, here send this request to the server. Don't bother me unless the server responds, and once the server responds (we have a "response"), call this method. This is called callback. The method is called at a later point, when the response comes.
So the statement
x.ajaxMethod(param1,JScallBackFunction);
(assuming that it does gets a XmlHttpRequest, initializes it and calls the send method on it*) actually does two things:
Sends the Ajax request
Registers a call back function that will be called when the server responds (when we have an response). JScallBackFunction will be called when there is an response from the server.
But since this is an asynchronous request, the browser does not "wait" instead it continues to the next statement (if there is one) after the Ajax call and executes it.
So, alert("Line after ajaxMethod"); will be executed immediately.
*If this does not make any sense for you, this is how an Ajax request is actually "created" and "sent". This article may help you understand.

Categories