When a request is sent to the server, we need to perform some response-based tasks.
Whenever readyState changes, the onreadystatechange event is triggered.
The readyState attribute stores the status information of XMLHttpRequest.
The following are three important properties of the XMLHttpRequest object:
property | describe |
---|---|
onreadystatechange | Stores a function (or function name) that will be called whenever the readyState property changes. |
readyState | The status of XMLHttpRequest exists. Changes from 0 to 4. 0: The request is not initialized 1: Server connection established 2: Request received 3: Request is being processed 4: The request is completed and the response is ready |
status | 200: "OK" 404: Page not found |
In the onreadystatechange event, we specify the tasks to be performed when the server response is ready to be processed.
When readyState equals 4 and the status is 200, the response is ready:
Note: The onreadystatechange event is triggered 4 times (0 - 4), respectively: 0-1, 1-2, 2-3, 3-4, corresponding to each change of readyState.
A callback function is a function that is passed as a parameter to another function.
If you have multiple AJAX tasks on your site, you should write a standard function for creating an XMLHttpRequest object and call that function for each AJAX task.
The function call should contain the URL and the task to be performed when the onreadystatechange event occurs (which may be different for each call):