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.
Using jQuery, let's write an example to test both asynchronous and synchronous requests.
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 argument async
, that is used to set what kind of request is to be sent. Inside this function, we used the ajax
method which will be used to send an AJAX request. For the ajax
method, the first argument will be URL
to 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"
, the success
callback function that will be executed once we receive the response and the async
property which tells if the request is to be sent as synchronous
or asynchronous
.
Line 26: Call the sendRequest
method with false
as an argument. The false
value for the argument is set to async
property 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 the success
handler of the request is completed.
Line 29: Call the sendRequest
method with true
as an argument. The true
value for the argument is set to async
property of the ajax
request. 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 the ajax
method. Once we receive the response the success handler will be executed.
Free Resources