What is a synchronous request in AJAX?
Usually, we will send the AJAX request to be asynchronous. If we send a request asynchronously, the code execution will not wait for the response. Other codes are executed until the response is received. Once the response is received, that will be processed by the callback provided to the AJAX method.
The synchronous request means after making a request; the code execution will be blocked until the response is received. After sending the synchronous request, we cannot interact with the browser tab until the response is received.
Example
Using jQuery, let's write an example to test both asynchronous and synchronous requests.
Explanation
In the code snippet above:
Line 6: Load the jQuery library using the CDN link of the library.
Lines 8–22: Create a function
sendRequest. This function takes one argumentasync, that is used to set what kind of request is to be sent. Inside this function, we used theajaxmethod which will be used to send an AJAX request. For theajaxmethod, the first argument will beURLto which the request is to be made. The second argument is options for the request. In the options, we set the request type as"GET", thesuccesscallback function that will be executed once we receive the response and theasyncproperty which tells if the request is to be sent assynchronousorasynchronous.Line 26: Call the
sendRequestmethod withfalseas an argument. Thefalsevalue for the argument is set toasyncproperty of the ajax request. So the request will be sent as a synchronous request. In this case, until the response is received the code execution is blocked. So the console log at line 21 will not be executed until the execution of thesuccesshandler of the request is completed.Line 29: Call the
sendRequestmethod withtrueas an argument. Thetruevalue for the argument is set toasyncproperty of theajaxrequest. So the request will be sent as an asynchronous request. In this case, the code execution will continue without waiting for the response. So the console log at line 21 will be executed after calling theajaxmethod. Once we receive the response the success handler will be executed.
Free Resources