AJAX: Using the XMLHttpRequest Object and Fetch API
Learn two ways of using AJAX in JavaScript to send and receive data from a server using the XMLHttpRequest object and Fetch API.
Join the DZone community and get the full member experience.
Join For FreeWe can use AJAX in JavaScript in two ways: using the XMLHttpRequest object and Fetch API. Fetch is a modern concept equivalent to XMLHttpRequest. It offers a lot of the same functionality as XMLHttpRequest, but is designed to be more extensible and efficient (MDN docs). In this article, I will introduce how to send and receive data from a server by using the XMLHttpRequest object and Fetch API through examples. I will also introduce errors that we may find and how to fix them.
Sending and Retrieving Data
The two most common methods for communicating between a client and server are GET and POST.
Using GET
If we are using XMLHttpRequest, the code looks like this:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// retrieve data from server
document.getElementById("demo").innerHTML = this.responseText;
}
};
// send data to server
xhttp.open("GET", "AjaxExample.php?", true);
xhttp.send();
}
</script>
</body>
</html>
If we are using Fetch, the code looks like this:
<!DOCTYPE html>
<html>
<body>
<h2>The Fetch API</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
fetch('AjaxExample.php?', {method: 'get'})
.then(function(response) {
// retrieve data from server
if(response.ok){
return response.text();}
})
.then(function(text){
document.getElementById("demo").innerHTML = text;
})
}
</script>
</body>
</html>
The AjaxExample.php file looks like this:
$data = $_GET['name'];
echo $data;
Using POST
If we want to send a large amount of data to the server, we can use the POST method. POST is more robust and secure than GET. The following examples use POST with XMLHttpRequest and FetchAPI:
XMLHttpRequest
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var json_upload = "json_name=" + JSON.stringify({name:"Ngoc Minh", time:"2:30 pm"});
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "AjaxExample.php");
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send(json_upload);
}
</script>
</body>
</html>
Fetch
<!DOCTYPE html>
<html>
<body>
<h2>The Fetch API</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var json_upload = "json_name=" + JSON.stringify({name:"Ngoc Minh", time:"2:30 pm"});
fetch('AjaxExample.php', {
method: 'post',
headers: {
"Content-Type":"application/x-www-form-urlencoded"
},
body: json_upload })
.then(function(response) {
if(response.ok)
return response.text();
})
.then(function(data){
document.getElementById("demo").innerHTML = data;
})
}
</script>
</body>
</html>
AjaxExample.php looks like this:
$json_data = $_POST['json_name'];
$json = json_decode($json_data,true);
echo "<h2>Wellcome you, ".$json['name']." and ".$json['time']."</h2>"
Error Handling
Consider the following example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//retrieve data from server
document.getElementById("demo").innerHTML = this.responseText;
}
};
// send data to server
xhttp.open("GET", "AjaxExample.php?", true);
xhttp.send();
If I type AjxExample.php instead of AjaxExample.php, as in the following code:
xhttp.open("GET", "AjxExample.php?", true);
xhttp.send();
When we click the button, the following error will occur in the debug tool of the browser (I am using Chrome):
In the source code:
Now, if we want to display messages to viewers when errors occur, the above examples can change as follows:
XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
else
{
if(this.status==404)
document.getElementById("demo").innerHTML = "Not Found.";
else
if(this.status==403)
document.getElementById("demo").innerHTML = "Forbidden";
else
document.getElementById("demo").innerHTML = "Something wrong.";
}
}
};
xhttp.open("GET", "AjaxExample.php?", true);
xhttp.send();
Fetch:
fetch('AjaxExample.php?', {
method: 'get'})
.then(function(response) {
if(response.ok){
return response.text();
}
else{
if(response.status==404)
return Promise.reject("Not Found.");
else
if(response.status==403)
return Promise.reject("Forbidden.");
else
return Promise.reject("Something wrong.");
}
})
.then(function(text){
document.getElementById("demo").innerHTML = text;
})
.catch(function(err) {
document.getElementById("demo").innerHTML = err;
})
If we are using the Fetch API, when working with JSON data, the following error usually occurs:
We can solve this problem as follows:
let contentType = response.headers.get('content-type')
if (contentType.includes('application/json')) {
return response.json();
}
else if (contentType.includes('text/html')) {
return response.text();
}
Conclusion
There are a lot of helpful articles and documents about XMLHttpRequest and Fetch API, but hopefully, with this article, I have contributed another helpful article about them.
Opinions expressed by DZone contributors are their own.
Comments