• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Best Way To Learn And Adept Javascript AJAX Quickly

Best Way To Learn And Adept Javascript AJAX Quickly

By Sigit Prasetya Nugroho ∙ July 28, 2019 ∙ Javascript ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

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

tutorial Javascript AJAX Quickly

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

  • 1 What Is AJAX?
    • 1.1 How to use Javascript AJAX
    • 1.2 Create AJAX Javascript Object
    • 1.3 Determine the Handler Events Functions
    • 1.4 Determine the Method and URL
    • 1.5 Send Request
  • 2 How to send data to the server using Javascript Ajax
  • 3 Javascript AJAX Library
    • 3.1 JQUERY
    • 3.2 AXIOS
    • 3.3 Fetch API
  • 4 Conclusion

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

Trace AJAX Request Process Javascript Min

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. OPENEDThe open () method has been called, in this state the status header is 0
2. HEADERS_RECEIVEDThe send() method has been called, and the status header already exists.
3. LOADINGThe process of downloading data
4. DONEAJAX 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();

Javascript Ajax Post Json

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

Javascript Ajax Post Example

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

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com