Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] AJAX Call in JavaScript with Example

#1
AJAX Call in JavaScript with Example

by Vincy. Last modified on September 27th, 2022.

This is a pure JavaScript solution to use AJAX without jQuery or any other third-party plugins.

The AJAX is a way of sending requests to the server asynchronously from a client-side script. In general, update the UI with server response without reloading the page.

I present two different methods of calling backend (PHP) with JavaScript AJAX.

  1. via XMLHTTPRequest.
  2. using JavaScript fetch prototype.

This tutorial creates simple examples of both methods. It will be an easy start for beginners of AJAX programming. It simply reads the content of a .txt file that is in the server via JavaScript AJAX.

If you want to search for a code for using jQuery AJAX, then we also have examples in it.

ajax javascript

AJAX call via XMLHTTPRequest


This example uses XMLHttpRequest in JavaScript to send an AJAX request to the server.

The below script has the following AJAX lifecycle to get the response from the server.

  1. It instantiates XMLHttpRequest class.
  2. It defines a callback function to handle the onreadystatechange event.
  3. It prepares the AJAX request by setting the request method, server endpoint and more.
  4. Calls send() with the reference of the XMLHttpRequest instance.

In the onreadystatechange event, it can read the response from the server. This checks the HTTP response code from the server and updates the UI without page refresh.

During the AJAX request processing, it shows a loader icon till the UI gets updated with the AJAX response data.

ajax-xhr.php

<!DOCTYPE html>
<html>
<head>
<title>How to make an AJAX Call in JavaScript with Example</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
<style>
#loader-icon { display: none;
}
</style>
</head>
<body> <div class="phppot-container"> <h1>How to make an AJAX Call in JavaScript</h1> <p>This example uses plain JavaScript to make an AJAX call.</p> <p>It uses good old JavaScript's XMLHttpRequest. No dependency or libraries!</p> <div class="row"> <button on‌click="loadDocument()">AJAX Call</button> <div id="loader-icon"> <img src="loader.gif" /> </div> </div> <div id='ajax-example'></div> <script> function loadDocument() { document.getElementById("loader-icon").style.display = 'inline-block'; var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function() { if (xmlHttpRequest.readyState == XMLHttpRequest.DONE) { document.getElementById("loader-icon").style.display = 'none'; if (xmlHttpRequest.status == 200) { // on success get the response text and // insert it into the ajax-example DIV id. document.getElementById("ajax-example").innerHTML = xmlHttpRequest.responseText; } else if (xmlHttpRequest.status == 400) { // unable to load the document alert('Status 400 error - unable to load the document.'); } else { alert('Unexpected error!'); } } }; xmlHttpRequest.open("GET", "ajax-example.txt", true); xmlHttpRequest.send(); }
</script> </body>
</html>

Using JavaScript fetch prototype


This example calls JavaScript fetch() method by sending the server endpoint URL as its argument.

This method returns the server response as an object. This response object will contain the status and the response data returned by the server.

As like in the first method, it checks the status code if the “response.status” is 200. If so, it updates UI with the server response without reloading the page.

ajax-fetch.php

<!DOCTYPE html>
<html>
<head>
<title>How to make an AJAX Call in JavaScript using Fetch API with Example</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
<style>
#loader-icon { display: none;
}
</style>
</head>
<body> <div class="phppot-container"> <h1>How to make an AJAX Call in JavaScript using Fetch</h1> <p>This example uses core JavaScript's Fetch API to make an AJAX call.</p> <p>JavaScript's Fetch API is a good alternative for XMLHttpRequest. No dependency or libraries! It has wide support with all major browsers.</p> <div class="row"> <button on‌click="fetchDocument()">AJAX Call with Fetch</button> <div id="loader-icon"> <img src="loader.gif" /> </div> </div> <div id='ajax-example'></div> <script> async function fetchDocument() { let response = await fetch('ajax-example.txt'); document.getElementById("loader-icon").style.display = 'inline-block'; console.log(response.status); console.log(response.statusText); if (response.status === 200) { document.getElementById("loader-icon").style.display = 'none'; let data = await response.text(); document.getElementById("ajax-example").innerHTML = data; } }
</script> </body>
</html>

An example use case scenarios of using AJAX in an application


AJAX is a powerful tool. It has to be used in an effective way wherever needed.

The following are the perfect example scenarios of using AJAX in an application.

  1. To update the chat window with recent messages.
  2. To have the recent notification on a social media networking website.
  3. To update the scoreboard.
  4. To load recent events on scroll without page reload.

We have seen how to keep on posting events into a calender using jQuery AJAX script in a previous article.
Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/09/...h-example/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] JavaScript – How to Open URL in New Tab xSicKxBot 0 28 12-03-2025, 02:57 AM
Last Post: xSicKxBot
  [Tut] AJAX File Upload with Progress Bar using JavaScript xSicKxBot 0 29 12-02-2025, 10:13 AM
Last Post: xSicKxBot
  [Tut] JavaScript – How to Open URL in New Tab xSicKxBot 0 1,857 08-21-2023, 10:25 AM
Last Post: xSicKxBot
  [Tut] AJAX File Upload with Progress Bar using JavaScript xSicKxBot 0 1,830 08-20-2023, 12:34 AM
Last Post: xSicKxBot
  [Tut] jQuery AJAX AutoComplete with Create-New Feature xSicKxBot 0 1,855 08-16-2023, 08:48 AM
Last Post: xSicKxBot
  [Tut] How to Wait 1 Second in JavaScript? xSicKxBot 0 1,464 10-19-2022, 03:08 AM
Last Post: xSicKxBot
  [Tut] JavaScript this Keyword xSicKxBot 0 1,443 09-14-2022, 02:01 PM
Last Post: xSicKxBot
  [Tut] JavaScript News Ticker xSicKxBot 0 1,266 08-29-2022, 08:37 AM
Last Post: xSicKxBot
  [Tut] Generate PDF from HTML with JavaScript and Example xSicKxBot 0 1,476 05-13-2022, 10:43 AM
Last Post: xSicKxBot
  [Tut] PHP Pagination Code with Search using AJAX xSicKxBot 0 1,564 04-04-2022, 09:10 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016