Working with AJAX in multiple Technologies

Yogi
CodeOdin
Published in
4 min readDec 26, 2017

Every web developer uses AJAX in his or her projects at sometime or the other. AJAX, as we all know is a term associated with JavaScript, but we can use it with different web technologies.

Here I will teach you how to use AJAX in JavaScript, jQuery, React & Angular.

What is AJAX — If you are a beginner?

AJAX — Asynchronous JavaScript & XML is used to update parts of a web page without reloading the whole page. This means the web page will be updated in asynchronous manner.

For becoming a Good Web Developer, it is a requirement that you should know AJAX, to make creative features in websites.

AJAX with JSON

In this tutorial I will teach you how to read a JSON file and show its data on your web page. The JSON file will be read with AJAX.

“A JSON is a file type which is used to exchange data in the web. It supports data structures like object and array and it is easy to write and read data from JSON.”

I have created rooms.json file which contains the following data:

{
“id”: 1,
“room”: “2 Room Set”,
“items”: [ “bed”, “chest of drawers”, “table” ]
}

AJAX with JavaScript

In my web page, I will create a div, and that will be the place where the data from this json file will be shown.

<div id=“jsonDiv”></div>

Now in your page head section add the following JavaScript code which will read this json and show it on this div.

<script>
var xmlhttp = new XMLHttpRequest();
var url = “rooms.json”;

xmlhttp.open(“GET”, url, true);
xmlhttp.send();

xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“jsonDiv”).innerText = this.responseText;
}
};
</script>

Explanation:- First I have created the XMLHttpRequest variable which will be used to make the AJAX request.

Then with the .open() method the AJAX request is initialized.

The 3 parameter passed to the .open() methods are:

  1. Method: The HTTP method to use, such as “GET”, “POST”, “PUT”, “DELETE”.
  2. URL: The url to where you make the request. Here this url is rooms.json file.
  3. Async: A Boolean value indicating whether or not to perform the operation asynchronously.

The XMLHttpRequest.send() method sends the AJAX request and returns immediately.

Once the AJAX request completes the .onreadystatechange() method is called up where I am showing the AJAX response ( which is the rooms.json file’s data). I will show the response in the div.

The rooms.json file’s data gets shown up inside the div. See the below screenshot which shown the output of my code:

AJAX with jQuery

jQuery is absolutely brilliant when making AJAX request. In jQuery we can use the jQuery AJAX Method to fetch this JSON files asynchronously.

This is how to use the .ajax() method here.

$.ajax({
url: “rooms.json”,
success: function (result, status, xhr) {
$(“#jsonDiv”).html(result);
},

error: function (xhr, status, error) {
alert(“Some AJAX error”);
}
});

The 2 important things to note here is the success and error callback function. Inside the success callback the AJAX response is shown (inside the div), while if there is an error then the alert message box is shown.

AJAX with Angular 6

Angular 6 is the latest version of Angular. It is in great demand today so I decided to include it to on this tutorial.

In your Angular app put the rooms.json file inside the assets folder.

Then Import the HttpClient class in your componet:

import { HttpClient } from ‘@angular/common/http’;

Now do the Dependency Injection for the HttpClient class inside the constructor of the component.

constructor(private http:HttpClient) {
}

Next create a variable where the AJAX response will be stored.

Roomsdata;

Create the ngOnInit() method which will be created when the component is created. Inside it you assign the AJAX response to some variable. I will show this variable’s data on the view using interpolation.

ngOnInit() {
this.http.get(‘rooms.json’, {responseType: ‘text’}).subscribe(data=>{
roomsData=data;
})
}

And finally the component’s code with interpolation.

@Component({
selector: ‘client’,
template: `<h2>Rooms JSON</h2>
{{roomsData}}
`
})

The full component code will be:

import { HttpClient } from ‘@angular/common/http’;
@Component({
selector: ‘client’,
template: `<h2>Rooms JSON</h2>
{{roomsData}}
`
})

export class ClientComponent implements OnInit {
constructor(private http:HttpClient) {
}

roomsData;
ngOnInit() {
this.http.get(‘rooms.json’, {responseType: ‘text’}).subscribe(data=>{
roomsData=data;
})
}
}

AJAX with React

In react you can use the fetch API code to get the rooms.json file data.

fetch('rooms.json')
.then(res => res.json())
.then(data => console.log(data))

Conclusion
I hope that you would love this AJAX tutorial and understand the importance of AJAX in web development. This tutorial should give you a great base for further learning.

Please provide me a clap” and this will help keep me motivated to write new articles on Medium.

As always, leave a comment about your thoughts.

--

--

Yogi
CodeOdin

ASP. NET Core Full Stack Developer — Frequently posting web development tutorials & articles. I have a passion for understanding things at a fundamental level.