cft

AJAX

AJAX is an acronym for Asynchronous JavaScript And XML, it is a set of web technologies to send and receive data from client to server asynchronously. It does all of this behind the scenes and that does not require reloading the page.


user

Tejeshwer Singh Sachdeva

2 years ago | 6 min read

AJAX is an acronym for Asynchronous JavaScript And XML, it is a set of web technologies to send and receive data from client to server asynchronously. It does all of this behind the scenes and that does not require reloading the page.

Without AJAX we call the URL and that makes a common request to the server and in return, the server sends a common response to the request made. But in the case of AJAX, the requests are made in the background which allows getting a response without even reloading the page.

To work with AJAX first we make an AJAX call using JavaScript or some other library like jQuery or Axios. The server in response to the AJAX call will then return the data in XML/JSON format.

XMLHttpRequest(XHR) Object

The XHR object is actually an API in form of an object, it is considered as an object because it has properties and methods attached to it. The XHR is provided by the browser’s JavaScript environment and the methods present within the XHR objects allows us to transfer data between client and server. Although it is mostly used with HTTP it can also be used with web protocols other than just HTTP, along with that it not only just works with XML but is effective with JSON and plain text also.



Fetching a text file

Let’s say that you have a text file on your local machine or your server and now you want to access that file in your web application well in that case here are the necessary steps you’ll need to follow:-
1.) Creating the XHR object:- The XHR object can be created/initialized using a pattern similar to what we use while initializing normal objects in JavaScript.
var xhr = new XMLHttpRequest();

2.) Call the specific method for our respective task:- Once you’ve created your XHR object you’ll now need to call the open function for our task to open the file in our server/system. This method takes in 3 parameters: first is the type of request we’re going to make, second is the URL/filename for our file, and lastly a boolean value for whether we want our call to be asynchronous or not.
xhr.open('GET', 'sample.txt', true)

3.) Initialize the onload():- Once you’ve called the open method you’ll now need to specify what to do next with the file you wanted. The onload is a variable that contains a function with the set of instructions to be performed on data we received.
xhr.onload = function () {
if(this.status == 200) {
console.log(this.responseText);
}
}

If instead of onload you use the onreadystatechange you’ll have to add an additional check for the readyState apart from the status.
xhr.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}

4.) Call the send function:- Once you are done with all the above steps you now need to call the send function, which sends the request to the server.
xhr.send();



Fetching a JSON file

Having fetched the text file you now want to level up and fetch the JSON file using AJAX, and as you might have guessed it is almost similar to how we fetch a simple text file, but there is a catch to it mentioned in the steps below:
1.) Creating the XHR object:- The XHR object can be created/initialized using a pattern similar to what we use while initializing normal objects in JavaScript.
var xhr = new XMLHttpRequest();

2.) Call the specific method for our respective task:- This part also remains similar only we change the name of our text file with a JSON file.
xhr.open('GET', 'user.json', true)

3.) Initialize the onload():- In case of fetching a JSON file, you’ll also have to parse the result that you get into JSON so that you can then use them similar to how you use objects in JavaScript.
xhr.onload = function () {
if(this.status == 200) {
var users = JSON.parse(this.responseText);
console.log(users.name);
console.log(users);
}
}

4.) Call the send function:- Once you are done with all the above steps you now need to call the send function, which sends the request to the server.
xhr.send();



Fetching an external API

Congratulations! you now know how to fetch a file on your local system using AJAX. Now let’s step up and use AJAX to fetch an API.

The steps required to fetch an API using AJAX are again similar to how we would have fetched a normal text file, but as you might have guessed there are some catches to it and these are mentioned in the steps below:
1.) Creating the XHR object:-
var xhr = new XMLHttpRequest();

2.) Call the specific method for our respective task:- In this step, we replace the name of our file with the external API link from where we want to fetch our data.
xhr.open('GET', 'https://api.github.com/users', true)

3.) Initialize the onload():- This part remains the same as it was in the case of fetching a JSON file from our local system.
xhr.onload = function () {
if(this.status == 200) {
var users = JSON.parse(this.responseText);
console.log(users);
}
}

4.) Call the send function:-
xhr.send();




AJAX & PHP

We can use AJAX with our PHP code to get or post the data without even reloading the page every time we do that.

Get Request

To get/post requests using our PHP file first create an HTML file with a button. The button will have an onclick event, and within the click event, we need to perform the following steps:
1.) Creating the XHR object:-
var xhr = new XMLHttpRequest();

2.) Call the specific method for our respective task:- In this step, we call our PHP file instead of text/JSON/API. Along with the name of our file, we also pass in a parameter with a value that will be accessed by our PHP file.
xhr.open('GET', 'process.php?name="My_Name"', true)

3.) Initialize the onload():- In case of fetching a JSON file, you’ll also have to parse the result that you get into JSON so that you can then use them similar to how you use objects in JavaScript.
xhr.onload = function () {
if(this.status == 200) {
console.log(this.responseText);
}
}

4.) Call the send function:- Once you are done with all the above steps you now need to call the send function, which sends the request to the server.
xhr.send();

Our HTML file is all set now with the required JavaScript. Now let’s focus on our process.php file.

In our PHP file, we first check for the GET request and whether we are provided the required parameter or not.
<?php
if(isset($_GET['name'])) {
echo 'GET: Your name is '.$_GET['name'];
}

Run the files now and you’ll have “GET: Your name is My_Name” printed in the console.

Post Request

Now as we are done with the GET request let’s catch up with the POST request. In this, we create another check in our process.php file for the POST request which is similar to the GET request check we did earlier.
<?php
if(isset($_POST['name’])) {
echo ‘POST: Your name is ‘.$_POST['name'];
}

if(isset($_GET['name'])) {
echo 'GET: Your name is '.$_GET['name'];
}

Now let’s focus on our POST-AJAX request. For this, we create a form with a text input field and a submit button. The steps for this method are:
1.) Get the value from the input text field:- Once you have created the HTML structure for your page, the first thing you need to do within the event listener function is to grab the value within the input field.
var name = document.getElementBYId('name').value;
Then you have to set a params variable which will be later on passed to our process.php file.
var params = "name="+name;

1.) Creating the XHR object:-
var xhr = new XMLHttpRequest();

2.) Call the specific method for our respective task:- In this step, we call our PHP file instead of text/JSON/API. And the GET is replaced by POST
xhr.open('POST', 'process.php', true)

3.) Set our request header:- In case of a POST request we’ll need to have an extra step to set a header.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

3.) Initialize the onload():-
xhr.onload = function () {
if(this.status == 200) {
console.log(this.responseText);
}
}

4.) Call the send function:- Once you are done with all the above steps you now need to call the send function, which sends the request, and along with that we’d also need to pass the params variable created earlier so that the PHP file can access it and print the name to the console.
xhr.send(params);

Once we have done these basics steps we can then create a database and interact with it using a similar AJAX fashion, the only thing that would change will be the code within the PHP file to connect to the database and perform certain queries.


!! This blog was written while going through “AJAX Crash Course” on YouTube by Brad Traversy(Traversy Media).

Upvote


user
Created by

Tejeshwer Singh Sachdeva

I am a Front-End Developer based in India. I am currently pursuing my Bachelors in Computer Science and Engineering from ITM University, Gwalior. Apart from that, I am an all-time explorer in the field of web & app development👨‍💻.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles