In this article, we will learn how to use jQuery to get a server response with an AJAX request. The jQuery ajax() method handles basic AJAX functions in jQuery. It talks to the server using asynchronous HTTP requests.
Syntax:
How to use readyState?
Before using readyState, we need to send a request to the server using XMLHttpRequest and store the response in a variable. Then, we use onreadystatechange, which holds a function that checks the status of the request. This function runs every time the readyState property changes.
Syntax:
Example: Below example illustrates the use of readyState=0.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Ready states of a request in ajax.</title>
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Hey Geek,</h1>
<h3>Welcome to GeeksforGeek!</h3>
<button type="button" onclick="stateChange()">
Update Text
</button>
</div>
<script>
function stateChange() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 0) {
document.getElementById("container").innerHTML
= this.responseText + "Status Text: " +
this.statusText;
}
};
xhttp.open("GET", "gfgInfo.txt", true);
xhttp.send();
}
</script>
</body>
</html>
readyState=3: This state indicates that the request is still in progress and data is being received. You can access this data through responseText, but it might not be complete yet since the request isn’t finished.
Example: Below example illustrates the use of readyState=3.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Ready states of a request in ajax.</title>
<style>
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Hey Geek,</h1>
<h3>Welcome to GeeksforGeek!</h3>
<button type="button" onclick="stateChange()">
Update Text
</button>
</div>
<script>
function stateChange() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 3) {
document.getElementById("container").innerHTML =
this.responseText + "Status Text: " +
this.statusText;
}
};
xhttp.open("GET", "gfgInfo.txt", true);
xhttp.send();
}
</script>
</body>
</html>