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.