How to make calls without Ajax in vanilla Javascript. Using Ajax requires jQuery, whilst it is a convenience, including the whole jQuery library for just Ajax is overboard.
Here is a function that replaces Ajax (plus jQuery) and allows you to do GET, PUT, POST and DELETE HTTP calls.
This is all done with XMLHttpRequest (XHR).
function doAPIcall(type, url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
if (callback) callback(data);
}
};
xmlhttp.open(type, url, true);
xmlhttp.send();
} Calling the function as a GET request and assigning the returned data to the ouputHere element:
doAPIcall(
"GET",
"https://domain.com/api/index.php?type=SELECT",
function (data) {
document.getElementById("outputHere").innerHTML = data; //Place data at #outputHere
}
);
<div id="outputHere"></div>
A callback is used with the function because we cannot return the data straight away… it hangs for a fraction whilst making the call. This appears as a function inside a function.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…