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

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/09/ajax-call-in-javascript-with-example.jpg" width="550" height="413" title="" alt="" /></div><div><div class="modified-on" readability="7.1666666666667"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 27th, 2022.</div>
<p class="p1">This is a <strong>pure JavaScript solution to use AJAX without jQuery</strong> or any other third-party plugins.</p>
<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>
<p>I present two different methods of calling backend (PHP) with JavaScript AJAX.</p>
<ol>
<li>via XMLHTTPRequest.</li>
<li>using JavaScript&nbsp;<em>fetch</em> prototype.</li>
</ol>
<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>
<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>
<p><img 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/20...00x225.jpg 300w, https://phppot.com/wp-content/uploads/20...68x576.jpg 768w, https://phppot.com/wp-content/uploads/20...script.jpg 960w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>AJAX call via XMLHTTPRequest</h2>
<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>
<p>The below script has the following AJAX lifecycle to get the response from the server.</p>
<ol>
<li>It instantiates <code class="language-php-template">XMLHttpRequest</code> class.</li>
<li>It defines a callback function to handle the <code class="language-php-template">onreadystatechange</code> event.</li>
<li>It prepares the AJAX request by setting the request method, server endpoint and more.</li>
<li>Calls send() with the reference of the <code class="language-php-template">XMLHttpRequest</code> instance.</li>
</ol>
<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>
<p>During the AJAX request processing, it shows a loader icon till the UI gets updated with the AJAX response data.</p>
<p class="code-heading">ajax-xhr.php</p>
<pre class="prettyprint"><code class="language-php-template">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How to make an AJAX Call in JavaScript with Example&lt;/title&gt;
&lt;link rel='stylesheet' href='style.css' type='text/css' /&gt;
&lt;link rel='stylesheet' href='form.css' type='text/css' /&gt;
&lt;style&gt;
#loader-icon { display: none;
}
&lt;/style&gt;
&lt;/head&gt;
&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(); }
&lt;/script&gt; &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>Using JavaScript <em>fetch</em> prototype</h2>
<p>This example calls JavaScript <em>fetch()</em> method by sending the server endpoint URL as its argument.</p>
<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>
<p>As like in the first method, it checks the status code if the “<em>response.status”</em> is 200. If so, it updates UI with the server response without reloading the page.</p>
<p class="code-heading">ajax-fetch.php</p>
<pre class="prettyprint"><code class="language-php-template">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How to make an AJAX Call in JavaScript using Fetch API with Example&lt;/title&gt;
&lt;link rel='stylesheet' href='style.css' type='text/css' /&gt;
&lt;link rel='stylesheet' href='form.css' type='text/css' /&gt;
&lt;style&gt;
#loader-icon { display: none;
}
&lt;/style&gt;
&lt;/head&gt;
&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; } }
&lt;/script&gt; &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2>An example use case scenarios of using AJAX in an application</h2>
<p>AJAX is a powerful tool. It has to be used in an effective way wherever needed.</p>
<p>The following are the perfect example scenarios of using AJAX in an application.</p>
<ol>
<li>To update the chat window with recent messages.</li>
<li>To have the recent notification on a social media networking website.</li>
<li>To update the scoreboard.</li>
<li>To load recent events on scroll without page reload.</li>
</ol>
<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>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/ajax-javascript/#top" class="top">↑ Back to Top</a> </p>
</div>


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



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016