Programming Tips - Can you do AJAX without jquery?

Date: 2008oct5 Language: javaScript Keywords: sample, kickstart, tutorial Keywords: ajax, without, jquery, fetch Q. Can you do AJAX without jquery? A. (This article is basically obsolete, now its better to use fetch() ) Entire books have been written about it but its just not that hard. Here's some a simple example. It displays a button that when pressed displays the time on the server. -------8<------------ file get_time.html -------------------------------
<script src=get_time.js></script> <button onClick="getServerTimeWithAjax()">Get Time on Server</button>
-------8<------------ file get_time.js -------------------------------
// A browser independent function to get the AJAX object. // I can't say I made this up. function getAjax() { return (!window.XMLHttpRequest)? (new ActiveXObject('Microsoft.XMLHTTP')):(new XMLHttpRequest()); } // You need a global variable for the request. var g_req = null; function stateChange() { var result, txt; if (g_req.readyState == 4) { result = false; if (g_req.status == 200) { result = true; txt = g_req.responseText; } g_req = null; // Set your global to null to show the request is done alert('Time on the server is ' + txt); // Display the result } } function getServerTimeWithAjax() { const url = 'get_time.php'; // Replace with your URL here if (g_req != null) { g_req.abort(); } // Perhaps set something to show you are working // setWorking(); g_req = getAjax(); g_req.onreadystatechange = stateChange; // your handler function (above). Do NOT do "stateChange()"'GET', url, true); g_req.send(null); }
-------8<------------ file get_time.php -------------------------------
<? print strftime('%T', time()); ?>