{"id":128395,"date":"2022-09-26T19:52:27","date_gmt":"2022-09-26T19:52:27","guid":{"rendered":"https:\/\/phppot.com\/?p=19530"},"modified":"2022-09-26T19:52:27","modified_gmt":"2022-09-26T19:52:27","slug":"ajax-call-in-javascript-with-example","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/09\/26\/ajax-call-in-javascript-with-example\/","title":{"rendered":"AJAX Call in JavaScript with Example"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1666666666667\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on September 27th, 2022.<\/div>\n<p class=\"p1\">This is a <strong>pure JavaScript solution to use AJAX without jQuery<\/strong> or any other third-party plugins.<\/p>\n<p>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.<\/p>\n<p>I present two different methods of calling backend (PHP) with JavaScript AJAX.<\/p>\n<ol>\n<li>via XMLHTTPRequest.<\/li>\n<li>using JavaScript&nbsp;<em>fetch<\/em> prototype.<\/li>\n<\/ol>\n<p>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 .<em>txt<\/em> file that is in the server via JavaScript AJAX.<\/p>\n<p>If you want to search for a <a href=\"https:\/\/phppot.com\/jquery\/dynamic-content-load-using-jquery-ajax\/\">code for using jQuery AJAX<\/a>, then we also have examples in it.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-19539\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/09\/ajax-javascript-550x413.jpg\" alt=\"ajax javascript\" width=\"550\" height=\"413\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/09\/ajax-javascript-550x413.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/09\/ajax-javascript-300x225.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/09\/ajax-javascript-768x576.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/09\/ajax-javascript.jpg 960w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>AJAX call via XMLHTTPRequest<\/h2>\n<p>This example uses&nbsp;<em><code class=\"language-php-template\">XMLHttpRequest<\/code><\/em> in JavaScript to send an <a href=\"https:\/\/phppot.com\/php\/ajax-programming-with-php\/\">AJAX request to the server<\/a>.<\/p>\n<p>The below script has the following AJAX lifecycle to get the response from the server.<\/p>\n<ol>\n<li>It instantiates <code class=\"language-php-template\">XMLHttpRequest<\/code> class.<\/li>\n<li>It defines a callback function to handle the <code class=\"language-php-template\">onreadystatechange<\/code> event.<\/li>\n<li>It prepares the AJAX request by setting the request method, server endpoint and more.<\/li>\n<li>Calls send() with the reference of the <code class=\"language-php-template\">XMLHttpRequest<\/code> instance.<\/li>\n<\/ol>\n<p>In the <code class=\"language-php-template\">onreadystatechange<\/code> 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.<\/p>\n<p>During the AJAX request processing, it shows a loader icon till the UI gets updated with the AJAX response data.<\/p>\n<p class=\"code-heading\">ajax-xhr.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;How to make an AJAX Call in JavaScript with Example&lt;\/title&gt;\n&lt;link rel='stylesheet' href='style.css' type='text\/css' \/&gt;\n&lt;link rel='stylesheet' href='form.css' type='text\/css' \/&gt;\n&lt;style&gt;\n#loader-icon { display: none;\n}\n&lt;\/style&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;div class=\"phppot-container\"&gt; &lt;h1&gt;How to make an AJAX Call in JavaScript&lt;\/h1&gt; &lt;p&gt;This example uses plain JavaScript to make an AJAX call.&lt;\/p&gt; &lt;p&gt;It uses good old JavaScript's XMLHttpRequest. No dependency or libraries!&lt;\/p&gt; &lt;div class=\"row\"&gt; &lt;button onclick=\"loadDocument()\"&gt;AJAX Call&lt;\/button&gt; &lt;div id=\"loader-icon\"&gt; &lt;img src=\"loader.gif\" \/&gt; &lt;\/div&gt; &lt;\/div&gt; &lt;div id='ajax-example'&gt;&lt;\/div&gt; &lt;script&gt; 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(); }\n&lt;\/script&gt; &lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<h2>Using JavaScript <em>fetch<\/em> prototype<\/h2>\n<p>This example calls JavaScript <em>fetch()<\/em> method by sending the server endpoint URL as its argument.<\/p>\n<p>This method returns the server response as an object. This response object will contain the status and the response data returned by the server.<\/p>\n<p>As like in the first method, it checks the status code if the \u201c<em>response.status\u201d<\/em> is 200. If so, it updates UI with the server response without reloading the page.<\/p>\n<p class=\"code-heading\">ajax-fetch.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;How to make an AJAX Call in JavaScript using Fetch API with Example&lt;\/title&gt;\n&lt;link rel='stylesheet' href='style.css' type='text\/css' \/&gt;\n&lt;link rel='stylesheet' href='form.css' type='text\/css' \/&gt;\n&lt;style&gt;\n#loader-icon { display: none;\n}\n&lt;\/style&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;div class=\"phppot-container\"&gt; &lt;h1&gt;How to make an AJAX Call in JavaScript using Fetch&lt;\/h1&gt; &lt;p&gt;This example uses core JavaScript's Fetch API to make an AJAX call.&lt;\/p&gt; &lt;p&gt;JavaScript's Fetch API is a good alternative for XMLHttpRequest. No dependency or libraries! It has wide support with all major browsers.&lt;\/p&gt; &lt;div class=\"row\"&gt; &lt;button onclick=\"fetchDocument()\"&gt;AJAX Call with Fetch&lt;\/button&gt; &lt;div id=\"loader-icon\"&gt; &lt;img src=\"loader.gif\" \/&gt; &lt;\/div&gt; &lt;\/div&gt; &lt;div id='ajax-example'&gt;&lt;\/div&gt; &lt;script&gt; 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; } }\n&lt;\/script&gt; &lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<h2>An example use case scenarios of using AJAX in an application<\/h2>\n<p>AJAX is a powerful tool. It has to be used in an effective way wherever needed.<\/p>\n<p>The following are the perfect example scenarios of using AJAX in an application.<\/p>\n<ol>\n<li>To update the chat window with recent messages.<\/li>\n<li>To have the recent notification on a social media networking website.<\/li>\n<li>To update the scoreboard.<\/li>\n<li>To load recent events on scroll without page reload.<\/li>\n<\/ol>\n<p>We have seen how to keep on <a href=\"https:\/\/phppot.com\/php\/events-display-using-php-ajax-with-clndr-calendar-plugin\/\">posting events into a calender using jQuery AJAX script<\/a> in a previous article.<br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/javascript\/ajax-javascript.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/javascript\/ajax-javascript\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":128396,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-128395","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128395","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=128395"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128395\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/128396"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=128395"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=128395"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=128395"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}