Categories: Development

Doing an Ajax call without jQuery

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).

CodePen example.

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago