How to Make an AJAX Request Without Using Frameworks or Libraries

There are a lot of JavaScript frameworks out there these days. It makes it harder to choose a front-end development workflow when starting a new project and write code that’s portable between different projects. Also, using a complex framework to solve a simple problem adds unneeded complexity and risk to a project, which makes getting that project out the door slower and more troublesome.

In the olden days, which in internet years was around 2008, browsers were horribly inconsistent. What worked in Internet Explorer wouldn’t work in Firefox. Chrome was still just a glimmer in Google’s eye. Using frameworks to perform simple tasks such as querying the DOM, performing animations, and making AJAX requests was required if you didn’t want to spend time rolling your own solution.

The downside to this was that relying on frameworks and libraries for every front end web development project has been cargo-culted through the years, despite that fact there have been a ton of advancements with browsers. (side note, if you’re ever unsure if browsers support a particular feature, check caniuse.com.)

Here’s a simple function I used in a recent project to handle AJAX requests. I took this approach because I was working on a background page of a Google Chrome extension, and felt that shoehorning a framework in to handle a few small tasks would be overkill. Here’s what I came up with:

<br />
function ajax(method, url, success, failure) {<br />
  var xhr = new XMLHttpRequest();<br />
  xhr.open(method, url, true);</p>
<p>  xhr.onreadystatechange = function() {<br />
    if(xhr.readyState == XMLHttpRequest.DONE) {<br />
      if(xhr.status &gt;= 200 &amp;&amp; xhr.status &lt;= 299) {<br />
        success(xhr.response);<br />
      } else {<br />
        failure(xhr.response);<br />
      }<br />
    }<br />
  }<br />
  xhr.send();<br />
  return xhr;<br />
}<br />

(Edit: Shout out to Matt Parsons for helping me improve this function based on a conversation from the Classic City Devs Slack Channel.)

The function is code takes four arguments: HTTP method, URL of the request, a success callback, and a failure callback.

Now, if I wanted to query and get some adorable animals from Reddit, I can do so in pure VanillaJS. Here’s an example:

<br />
function doStuff(response) { ... }<br />
function handleError(response) { ...}<br />
var url = 'https://www.reddit.com/r/aww.json';</p>
<p>ajax('GET', url, doStuff, handleError);<br />

Think before you npm install. Don’t include thousands of lines of a framework when you can solve the solution in a dozen lines of native JavaScript.

Want to be a more reliable developer? Check out a sample chapter from Dependable: Deliver Software on Time and within Budget

 

 

Click Here to Leave a Comment Below 0 comments

Leave a Reply: