Javascript AJAX is the primary components used to create dynamic web. AJAX stands for Asynchronous JavaScript and XML. JavaScript and XML work asynchronously in AJAX. Using AJAX in web applications, we can send and receive data from the server without reloading all pages as PHP does. In this tutorial, I will share what AJAX is? Also, how to use AJAX request in Javascript and some Javascript AJAX libraries.
You may have read some Javascript tutorials that I have shared, and on this occasion, you will get the answer, “Why do I have to master Javascript as web developers?”
In addition to manipulating DOM objects dynamically, one of the most essential functions of Javascript is to interact with the server dynamically, so that the web application will showing the information real-time.
Like HTML, XML (eXtensible Markup Language) is another variant of markup language. If HTML is designed to showing the data, XML is designed to load and carry the data. But keep in mind, in the era of modern programming, XML began to be abandoned and replaced by JSON (JavaScript Object Notation). The JSON format is easier to read and very lightweight, so JSON provides a better alternative to XML. I will not discuss in detail js JSON in this article, our focus is on Javascript AJAX.
Table of Contents
What Is AJAX?
AJAX stands for Asynchronous JavaScript And XML. AJAX is only a combination of:
- XMLHttpRequest (to request and send data from a web server)
- JavaScript and HTML DOM (for processing and displaying data on web pages dynamically)
The purpose of using AJAX is:
- Retrieve data from the server.
- Update web views without reloading web pages.
- Send data to the server in the background.
You can see the AJAX request process by inspecting elements on the browser page. The trick is:
- Press F12 or right-click on the webpage and select inspect element.
- Open the network tab and activate the XHR filter (XML HTTP Request).
How to use Javascript AJAX
To use the AJAX function in Javascript, you only need to call the XMLHttpRequest object. Following are the steps to using Javascript AJAX.
Create AJAX Javascript Object
1 | let ajx = new XMLHttpRequest(); |
Determine the Handler Events Functions
1 | ajx.onreadystatechange = function() { ... }; |
The onreadystatechange function will be executed every time the status of the XMLHttpRequest object changes.
To check whether AJAX has obtained the answer from the server using the following command.
1 2 3 | if(this.readyState == 4 && this.status == 200){ //... } |
Code state 4 means done, and 200 status means success.
The following is an explanation of the AJAX state code
1. OPENED | The open () method has been called, in this state the status header is 0 |
2. HEADERS_RECEIVED | The send() method has been called, and the status header already exists. |
3. LOADING | The process of downloading data |
4. DONE | AJAX operation is complete. |
1 | ajx.onloadstart = function() { ... } |
The event handler function executed before the request is sent
1 | ajx.onloadend = function() { ... } |
The event handler function executed after ajax request finishes has finished performing its task
1 | ajx.onerror = function() { ... } |
The event handler function executed when an error occurs.
1 | ajx.onprogress = function() { ... } |
The event handler function executed when ajax is doing its job
Determine the Method and URL
1 | ajx.open('GET', URL, true); |
There are three parameters in the open() method:
- GET is a request method, besides GET, it can use another header method, POST Request.
- URL is the URL address.
- true to execute AJAX asynchronously.
Send Request
1 | xhr.send(); |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | let ajax = new XMLHttpRequest() let obj = {} ajax.onreadystatechange=function(){ if(this.readyState == 4 && this.status == 200){ obj = this.responseText console.log(obj) } } ajax.onloadstart = function () { console.log("Start to load data from server...") } ajax.onloadend = function () { console.log("Finish !!") } ajax.onerror = function () { console.log("Failed to get data...") }; ajax.onprogress = function () { console.log("In progress, please wait...") }; ajax.open("GET", "https://api.github.com/users/seegatesite", true); ajax.send(); |
How to send data to the server using Javascript Ajax
After understanding how to retrieve data like the example above, AJAX can be used to send data and receive results from the server. See the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | let ajx = new XMLHttpRequest(); let url = "https://jsonplaceholder.typicode.com/posts"; let data = JSON.stringify({ title: "POST Request", body: "HELLO AJAX POST JAVASCRIPT", userId: 1 }); ajx.open("POST", url, true); ajx.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); ajx.onload = function () { console.log (this.responseText); }; ajx.send(data); |
Apart from using the XMLHttpRequest object, several Javascript libraries facilitate the use of AJAX such as jQuery, AXIOS, and Fetch API.
Javascript AJAX Library
JQUERY
JQuery simplifies the Javascript functions. To use AJAX in JQuery, see the following JQuery examples.
1 2 3 4 5 6 7 8 9 10 11 12 | $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", method: "POST", data: { title: "POST Request", body: "HELLO AJAX POST JAVASCRIPT", userId: 1 }, dataType: "JSON" }).done(function( data, textStatus, jqXHR ){ console.log(data); }) |
besides using the $.ajax() function, there are 2 other JQuery functions that can be used for AJAX processes such as load() and get()
load()
according to the jquery official website, the load function used to retrieve data from the server and be placed on specified HTML elements.
1 | $( "#result" ).load( "https://api.github.com/users/seegatesite" ) |
get()
Used to load data from a server using HTTP GET request method.
1 2 3 | $.get("https://api.github.com/users/seegatesite", function(data, status){ console.log(data) }); |
AXIOS
Axios is very familiar with Developers, especially Javascript web developers. Axios is known as the Promise based HTTP client. Where Axios prioritizes returning promises rather than calling callbacks. The most common thing we can do with Axios is an HTTP request from the browser or making an HTTP request with Node.js.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | axios.get('https://jsonplaceholder.typicode.com/posts/') .then(function (response) { let result = response.data.map(post => { console.log(post) }).join(""); console.log(result); }) .catch(function (error) { console.log(error); }) .then(function () { console.log("Done"); }); |
We will more often meet AXIOS when using some Javascript frameworks such as Angular, React And NodeJS
Fetch API
The fetch method is an API supported by modern browsers. The Fetch method is present since the ES6 era. And the use of fetch similar to the AXIOS library.
What are the differences between XMLHttpRequest and Fetch?
- Fetch will return a promise.
- By default, fetch will not send or receive cookies from the server.
- Fetch can be used in web browsers as well as Nodejs with node-fetch modules.
Example:
1 2 3 4 5 6 7 | fetch('https://jsonplaceholder.typicode.com/posts/') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(JSON.stringify(myJson)); }); |
We can add several query string such as header, method, data using the following command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | fetch(url, { method: "POST", // *GET, POST, PUT, DELETE, etc. mode: "cors", // no-cors, cors, *same-origin cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached credentials: "same-origin", // include, *same-origin, omit headers: { "Content-Type": "application/json", // "Content-Type": "application/x-www-form-urlencoded", }, redirect: "follow", // manual, *follow, error referrer: "no-referrer", // no-referrer, *client body: JSON.stringify(data), // body data type must match "Content-Type" header }) .then(response => response.json()); |
Conclusion
The AJAX function used to optimize the user experience. The use of AJAX will meet the standardization of modern dynamic web creation.
Hopefully, the above article helps you to understand and determine the AJAX Javascript libraries that you will use.
Reference : https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
Leave a Reply