Home » AJAX

AJAX Request

AJAX Request: In this tutorial, we are going to learn about the AJAX requests with syntaxes and examples.
Submitted by Siddhant Verma, November 19, 2019

We have talked briefly about what AJAX is and how to make AJAX requests? In this article, we'll dive deeper into AJAX requests by seeing the code in action and also understand every line of code,

    var xhr= new XMLHttpRequest();

Output:

Creates a new instance of the XMLHttpRequest() object. 

The first step is to create a new instance of the XMLHttpRequest() object by using the "new" keyword. We now have all the methods and properties attached to this xhr variable and we can actually see them by logging in to the console.

The next step will be to fire an event when the readyState of this object changes. Remember, we talked about the onreadyStatechange and how the readyState attains certain values based on which we can know the status of the request whether it is sent, yet to be sent, in process, completed, etc. We can do all this by firing a function which is handled by the event handler onreadystatechange so let's do this,

    XHR.onreadystatechange=function(){  
    }

Now inside this function, we'll check the readyState and since we want the request to be processed completely we need the readyState to have a value of 4 (Remember the value 4 indicated successful completion of the request?)

    XHR.onreadystatechange=function(){
        if(XHR.readyState==4){    
        }
    }

Now we'll check for a status of 200 and we can get the response from the API inside this. In all the other cases we can be assured that there was some problem,

XHR.onreadystatechange=function(){
  if(XHR.readyState==4){
    if(XHR.status==200){
    document.write(XHR.responseText);
    }
    else{
      console.log("There was a problem!");
    }
  }
}

Now there are two things left- to tell our object where to hit and what kind of request we're making and send back the data.

XHR.open("GET",url);
XHR.send();

And anywhere we can specify the URL by storing it in a variable and passing it inside the open() method.

You can use the above code as a boilerplate for making XHR requests. Let's make a simple GET request to an API and display the response on the HTML page.

Index.html:

<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>

    <div class="content">
        <h2>Today's thought</h2>
        <blockquote>

            <span>By Github Zen API</span>
        </blockquote>
    </div>

</body>
<script>
</script>

</html>

styles.css:

body {
	margin: 0;
	padding: 0;
	background: tomato;
}

.content {
	padding: 20px;
	margin: 20px;
	text-align: center;
}

h2 {
	text-transform: uppercase;
	color: aqua;
	font-size: 48px;
	font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
	letter-spacing: 4px;
}

blockquote {
	font-size: 1.4em;
	width: 60%;
	margin: 50px auto;
	font-family: Open Sans;
	font-style: italic;
	color: #555555;
	padding: 1.2em 30px 1.2em 75px;
	border-left: 8px solid #78C0A8;
	line-height: 1.6;
	position: relative;
	background: #EDEDED;
}

blockquote::before {
	font-family: Arial;
	content: "\201C";
	color: #78C0A8;
	font-size: 4em;
	position: absolute;
	left: 10px;
	top: -10px;
}

blockquote::after {
	content: '';
}

blockquote span {
	display: block;
	color: #333333;
	font-style: normal;
	font-weight: bold;
	font-family: Verdana, Geneva, Tahoma, sans-serif;
	margin-top: 1em;
}

Output

AJAX Request | Example Output 1

Now that we have our template setup, let's make a GET request to the Github Zen API, which will send us random quote when we make a GET request to it's endpoint.

const quote=document.querySelector('blockquote');
  var XHR=new XMLHttpRequest();
  XHR.onreadystatechange=function(){
  if(XHR.readyState==4){
    if(XHR.status==200){
    quote.innerHTML=XHR.responseText;
    }
    else{
      console.log("There was a problem!");
    }
  }
}
XHR.open("GET","https://api.github.com/zen");
XHR.send();

Output

AJAX Request | Example Output 2

Great! Now you have successfully learnt how to write AJAX requests using the XHR method? This is the basic concept behind consuming APIs on the frontend. Every time you reload the page, you will get a different quote from the Github Zen API.







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.