DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. AJAX: Using the XMLHttpRequest Object and Fetch API

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.

Ngoc Minh Tran user avatar by
Ngoc Minh Tran
CORE ·
Nov. 11, 17 · Tutorial
Like (5)
Save
Tweet
Share
15.96K Views

Join the DZone community and get the full member experience.

Join For Free

We 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):

Image title

In the source code:

Image title

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:

Image title

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.

API AJAX Fetch (FTP client) Object (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Remote Debugging Dangers and Pitfalls
  • Beginners’ Guide to Run a Linux Server Securely
  • Load Balancing Pattern
  • Asynchronous HTTP Requests With RxJava

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: