JS Ajax Request

Rubleen Kaur
Last Updated: May 13, 2022

Introduction

Ajax stands for Asynchronous Javascript And XML, and it is a means of loading large sets of data from the server and updating selective parts of a website without reloading it again and again. 

To perform Ajax communications, the javascript uses a particular object - the XMLHttpRequest. In this article, we will discuss what AJAX requests are and how these work.

 

 

Sending XMLHttprequests and receiving a response

Before starting to learn about the AJAX request, you will need to instantiate an XMLHttpRequest object, as shown below, 

var request = new XMLHttpRequest();

 

In the next step, we will send the request to the server using the open() method of the XMLHttpRequest object. The open() method accepts two parameters, the HTTP request method for AJAX requests and the URL to send the requests to.

 

For example,

request.open("GET""ninja.txt"); -Or- request.open("POST""add-ninja.php");

 

After receiving the AJAX request, we finally send the request to the server using the send() method.

 

request.send(); -Orrequest.send(body);

 

For the GET method, the data is sent as URL parameters. The data transmitted using the POST method will be sent to the server as part of the HTTP request body. 

 

AJAX GET request

The GET method in AJAX request is used to retrieve the data from the server, which does not require any change or manipulation in the database. 

Let’s consider the example to understand the concept better,

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Ajax GET request</title>
<script>
function displayFullName() {
    // Create the XMLHttpRequest object.
    var request = new XMLHttpRequest();

    // Instantiate the request object.
    request.open("GET""/examples/php/greet.php?fname=Coding&lname=Ninjas");

    // Define event listener for readystatechange event.
    request.onreadystatechange = function() {
        // Check if the request is complete and was successful.
        if(this.readyState === 4 && this.status === 200) {
            // Insert the response from server into an HTML element.
            document.getElementById("result").innerHTML = this.responseText;
        }
    };

    // Send the request to the server.
    request.send();
}
</script>
</head>
<body>
    <div id="result">
        <p>The div content will be replaced by the server response.</p>
    </div>
    <button type="button" onclick="displayFullName()">Display Full Name</button>
</body>
</html>

 

 OUTPUT
 

 

 

 

If the AJAX request is asynchronous, the send() method will return immediately after sending the request. The readyState is an integer that specifies the status of an HTTP request. For creating AJAX requests, the function which is assigned to the onreadystatechange event handler is called every time the readyState property is updated. The possible values of the readyState are listed in a tabular form below.

 

Value

State

Description

0UNSENTThe XMLHttprequest object is created in this state, but the open() method is not called yet.
1OPENEDThe open() method has been called, which indicates a server connection has been established.
2HEADERS_RECEIVEDThe send() method has been called.
3LOADINGThe server is processing the request.
4DONEThe request is processed, and the response is ready.

 

The status property returns a numerical HTTP status code for XMLHttpRequest’s response.A few common HTTP status codes are :

  • Status Code 200 - This means that everything is okay and the server has successfully processed the request.
  • Status Code 404 - This means ‘NOT FOUND.’ This happens when the server cannot find the requested page.
  • Status Code 503 - This means that the ‘SERVICE IS UNAVAILABLE.’ This happens when the server is temporarily unavailable.

Let’s see how we can use a greet.php website to create a person’s full name by joining the first and last name and displaying a greeting message.

<?php
if(isset($_GET["fname"]) && isset($_GET["lname"])) {
    $fname = htmlspecialchars($_GET["fname"]);
    $lname = htmlspecialchars($_GET["lname"]);
    
    // Create full name by joining first and last name.
    $fullname = $fname . " " . $lname;

    // Display a welcome greet.
    echo "Hello, $fullname! Welcome to Coding Ninjas.";
else {
    echo "Hi there! Welcome to our website.";
}
?>

 

Performing an AJAX POST request

The POST method in AJAX requests is used for submitting form data to the webserver. 

In the example below, we will see how to submit form data to the server using Ajax.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Ajax POST Demo</title>
<script>
function Comment() {
    // Create the XMLHttpRequest object.
    var request = new XMLHttpRequest();
    
    // Instantiate the request object.
    request.open("POST""/examples/php/confirmation.php");
    
    // Define event listener for readystatechange event.
    request.onreadystatechange = function() {
        // Check if the request is complete and was successful.
        if(this.readyState === 4 && this.status === 200) {
            // Insert the response from server into an HTML element.
            document.getElementById("result").innerHTML = this.responseText;
        }
    };
    
    // Retrieve the form data.
    var myForm = document.getElementById("myForm");
    var formData = new FormData(myForm);

    // Send the request to the server.
    request.send(formData);
}
</script>
</head>
<body>
    <form id="myForm">
        <label>Name:</label>
        <div><input type="text" name="name"></div>
        <br>
        <label>Comment:</label>
        <div><textarea name="comment"></textarea></div>
        <p><button type="button" onclick="Comment()">Post Comment</button></p>
    </form>    
    <div id="result">
        <p>The div content will be replaced by the server response.</p>
    </div>    
</body>
</html>

 

The code for the confirmation.php file is as follows,

<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars(trim($_POST["name"]));
    $comment = htmlspecialchars(trim($_POST["comment"]));
    
    // Check if form fields values are empty
    if(!empty($name) && !empty($comment)) {
        echo "<p>Hi, <b>$name</b>. Your comment has been received successfully.<p>";
        echo "<p>Here's the comment that you entered: <b>$comment</b></p>";
    } else {
        echo "<p>Fill all the fields in the form!</p>";
    }
else {
    echo "<p>Something went wrong. Please try again.</p>";
}
?>

 

For security reasons, Ajax does not allow us to make cross-domain requests. This means we can only make requests to URLs using the same domain name as the original page.

Frequently Asked Questions

  1. What is the full form of AJAX?
    Ans: AJAX stands for Asynchronous Javascript and XML.
     
  2. What is the use of GET in AJAX requests?
    Ans: The GET request in AJAX is used to retrieve the data from the server which does not require any change or manipulation in the database. 
     
  3. Mention a few common HTTP status codes.
    Ans: A few common HTTP status codes are :

→ Status Code 200 - This means that everything is okay and the server has successfully processed the request.

→ Status Code 404 - This means ‘NOT FOUND’. This happens when the server cannot find the requested page.

→ Status Code 503 - This means that the ‘SERVICE IS UNAVAILABLE’. This happens when the server is temporarily unavailable.

 

Key Takeaways

Hey everyone, so let’s brief out the article about the AJAX requests in Javascript. 

  • Ajax stands for Asynchronous Javascript And XML, and it is a means of loading large sets of data from the server and updating selective parts of a website without reloading it again and again. 
  • To perform Ajax communications, the javascript uses a particular object - the XMLHttprequest. In this article, we have discussed what AJAX requests are and how these work.
  • Furthermore, we have discussed the GET method in AJAX requests.

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

Happy Learning Ninjas!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think