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.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…