Javascript Ajax – Learn How To Make Ajax Requests In Plain Javascript

Javascript Ajax is a way to get and retrieve data from servers. It’s an important topic that every developer should know. Without ajax the data can’t be retrieved and sent from servers and APIs.

In this tutorial, I will teach you all you need to know about Ajax. First, we will discuss what is ajax. Secondly, we will learn how to make an Ajax request. Finally, we will finish with an example which demonstrates the Ajax requests.

So let’s get started.

What is Ajax?

Ajax stands for Asynchronous Javascript And XML. It is used to transport data between server to user and user to a server. The one thing that makes ajax more powerful is, it sends and gets data from a server without reloading a page.

 How to make an Ajax request?

We have one core constructor method XMLHttpRequest() , that takes care of everything about Ajax requests.

First of all, we have to create an instance of XMLHttpRequest().

Example:

var req = new XMLHttpRequest()

Now you can make a request to the API or a Server address.

After creating an instance, you need to open a request using .open() by providing a request method(either GET or POST) and the URL of the API or Server address.

req.open("GET", "https://jsonplaceholder.typicode.com/posts/1",true);

The first parameter in the req.open() method is an HTTP request method like GET, POST.

And The second parameter is the path URL of a rest API or back-end server.

The final parameter is a boolean value which tells the request is asynchronous or not.

Note: Here I am using JSONPlaceholder fake online rest APIs. If you use any server technology, just replace API with your server address.

Sending Request to the API

We have a request created. Now we have to send the request to the API.

You can send a request using the .send() method.

req.send();

Ok. Now we have made our first Ajax request. But, after making an Ajax request the server responded with a response.

So, we need to write a method to handle the server response. See the example below.

req.onreadystatechange = function() {
   var text = http.responseText;
   console.log(text);
};

The .onreadystatechange is a method which fires when the server is ready with a response.

When making the Ajax request, the server responded with a set of values. Below, I discussed some of them.

readyState: A number which indicates the state of a server. The number usually between (0 -4).

0 indicates – The request is not initialized yet.

1 indicates – The request connected to the server.

2 indicates – The request received by the server

3 indicates – The request is processing on the server

4 indicates – The request is completed and ready.

responseText: The response returns in a  string format

responseXML: The response returns in a XML format

responseURL:  Returns the URL of the response

status: The status code of server (e.g 200, 404)

statusText: The status text of a server.  (e.g “ok”, “error”)

Ok. Let’s grab the above code into one place for better understanding.

var req = new XMLHttpRequest();

req.open("GET", "https://jsonplaceholder.typicode.com/posts/1",true);

req.send();

req.onreadystatechange = function() {
    var text = req.responseText;
    console.log(text);
};

Till now, we learn how to make a request to API using Ajax to get data.

Let’s learn how to post data to API.

Posting data to API

To post data, just replace the HTTP method GET with POST and pass the data what you want to post in req.send() method.

Example:

var req = new XMLHttpRequest();

req.open("POST", "https://jsonplaceholder.typicode.com/posts",true);

req.send({

 	  title: 'simple post',
      body: 'simple post body',
      userId: 1
});

req.onreadystatechange = function() {
    var text = req.responseText;
    console.log(text);
};

As I told you earlier, I will finish this article with a simple example.

index.html

<!DOCTYPE html>
<html>
<head>
  <title>JSON Tutorial</title>
</head>
<body>

  <form>
    <input type="text" placeholder="post title" id="post_title" />
    <input type="text" placeholder="post body" id="post_body" />

    <button type="button" onclick="post()">Submit</button>
  </form>


  <div style="margin-top: 50px;">
    <button type="button" onclick="display_users()">Display Posts</button>

  </div>

  <script src="script.js"></script>
</body>
</html>

script.js

var post = function(){

  var title = document.getElementById('post_title');
  var body = document.getElementById('post_body');

  var req = new XMLHttpRequest();

  req.open("POST", "https://jsonplaceholder.typicode.com/posts",true);

  req.send({

   	  title: 'simple post',
        body: 'simple post body',
        userId: 1
  });

  req.onreadystatechange = function() {
      var text = req.responseText;
      console.log(text);
  };

}

var display_users = function(){

  var req = new XMLHttpRequest();

  req.open("GET", "https://jsonplaceholder.typicode.com/users");

  req.send();

  req.onreadystatechange = function() {
       
    var users = JSON.parse(req.responseText);
    console.log(users);
   
  };
}

The above example demonstrates how to get data and how to post data using Ajax.

I hope, this article may worth for you. If you have any doubts feel free to comment below.

Thanks for reading!

Happy [email protected]

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes2
No1
Powered by Helpful

Leave a Reply

Your email address will not be published. Required fields are marked *