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 can actually be both, sync and async.
It's a loosely defined buzzword. JS can make both. Synchronous calls are locking and should almost always be avoided though.
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.
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.