Last active
June 8, 2017 12:52
-
-
Save jmmarco/36beee991cbf7875e2be0b559a5d0f02 to your computer and use it in GitHub Desktop.
How to make an AJAX call without jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using vanilla JS (no jQuery) | |
// Your API key | |
var apiKey = "your-key-goes-here" | |
// Typically the URL will contain a key and other parameters (depending on the API you're making a call to) | |
var apiUrl = "the-API-URL-goes-here" + apiKey; | |
// Create the XMLHttpRequest object (allows us to make an AJAX call to an API) | |
// See more here: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest | |
var xhr = new XMLHttpRequest(); | |
// When the request is ready | |
xhr.onreadystatechange = function() { | |
// if the request is done | |
if (xhr.readyState == XMLHttpRequest.DONE) { | |
// and the status is 200 (which means we made it ok to the other end) | |
if (xhr.status == 200) { | |
// The response from the API is recieved via responseText | |
// parse the response so we can traverse it | |
var data = JSON.parse(xhr.responseText); | |
// Do something with this "data", append to the DOM, output to console.. | |
// If the requests fails or something's wrong.. | |
} else { | |
// Output the response text (proabably contains an error messsage to the console); | |
console.log(repsonseText); | |
} | |
} | |
}; | |
// Make the call | |
xhr.open("GET", apiUrl, true); | |
// Send the crendtials and acutal request | |
xhr.send(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment