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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago