Home » AJAX

AJAX Response

AJAX Response: In this tutorial, we will learn the AJAX response in detail, look at the server response properties, response methods and also code out a simple AJAX request whose response we will render to the DOM.
Submitted by Siddhant Verma, November 22, 2019

We already know that when we make an AJAX request, we get a response back from the endpoint. This response could be in any data format through JSON is widely used today. There are two response properties: responseText which contains the response data in a string format and the responseXML which contains the response data in XML format.

Since XML is an old school you probably won't find any maintained and popular APIs which send XML data. They mostly send back some JSON. We also have response methods to get us either specific header information using getResponseHeader() or all the header information through getAllResponseHeaders().

Let's work on a simple API and see an example where we can understand how this information looks like, how we can manipulate the responseText and render it to the DOM and learn how to use these properties and methods.

Inside your index.html file add the following code,

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles.css">
    <title>AJAX Request</title>

</head>

<body>
    <h2>User Profiles</h2>
    <h4>Header:</h4>
    <span class="headers"></span>
    <div class="container">

    </div>

</body>
<script>
</script>

</html>

Let's also add some styles to make it look a bit less boring,

body {
    background: linear-gradient(lightgreen, yellow);
}

li {
    list-style-type: none;
}

h2 {
    padding: 10px;
    margin: 4px;
    top: 20px;
    left: 450px;
    position: relative;
    font-size: 48px;
    color: #ffffff;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 2px;
}

.card {
    padding: 2px;
    margin: 12px;
    display: block;
    border: 2px solid whitesmoke;
    background: #ffffff;
    height: 150px;
    width: 400px;
    left: 450px;
    top: 20px;
    position: relative;
    color: lightslategray;
    text-transform: capitalize;
    font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
}

p {
    font-size: 20px;
    letter-spacing: 2px;
}

.headers {
    background: violet;
    font-size: 20px;
    color: #ffffff;
}

h4 {
    text-transform: uppercase;
    font-size: 24px;
}

Output

AJAX Response Example

Cool. Now under the script tag let's add some JavaScript. We'll make a GET request using AJAX to https://jsonplaceholder.typicode.com/users which will return us some users. This is a cool testing REST API that provides us with some dummy content.

Inside the request we'll populate our header and also display some user information that we get as a string from the API because remember, responseText has the typed string. So we'll convert this to a JSON object using JSON.parse(), iterate through it and push it to our template.

<script>
var url = 'https://jsonplaceholder.typicode.com/users';
const list = document.querySelector('.container');

var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
    if (XHR.readyState == 4) {
        if (XHR.status == 200) {
            document.querySelector('.headers').innerHTML += this.getAllResponseHeaders();
            renderDOM(XHR.responseText);
        } else {
            console.log("There was a problem!");
        }
    }
}
XHR.open("GET", url);
XHR.send();

function renderDOM(users) {

    users = JSON.parse(users);
    console.log(typeof(users));
    var userCnt = 0;
    users.forEach(user => {

        if (userCnt > 4)
            return;

        let userData = `
         <div class="card">
        <ul>
            <li>
         <p style="color:blue">Email: ${user.email}</p>
         <p style="color:red">Name:  ${user.name}</p>
         <p>Username:  ${user.username}</p>

            </li>
        </ul>
    </div>`
        list.innerHTML += userData;
        userCnt++;

    });
}
</script>

Output

AJAX Response Example

You can see how we have gathered all the header information using the getAllHeadersResponse() method and also passed the responseText inside a function that renders certain information on the DOM.

AJAX is a super old method, has a bulky syntax and is complex to use. More modern libraries like Axios, Jquery or the fetch API are used widely today for consuming API data on the frontend. However, it is important to understand how AJAX works.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.