Skip to content

Instantly share code, notes, and snippets.

@passandscore
Last active April 25, 2021 00:38
Show Gist options
  • Save passandscore/f7f76e04c514576922182d1c946a0d27 to your computer and use it in GitHub Desktop.
Save passandscore/f7f76e04c514576922182d1c946a0d27 to your computer and use it in GitHub Desktop.
AJAX template for creating a basic API based HTTP request.
//AJAX - DOM template
//Language: JavaScript
document.getElementById('btn').addEventListener('click', loadData)
function loadData() {
//create an new request object
const req = new XMLHttpRequest()
//Initialize the newly-created request object
req.open('GET', 'https://api.github.com/users')
//Define what you want to do with the data
req.onload = function() {
//Check server status (status code)
if (this.status === 200) {
//The response text is a JSON string returned from the server
const data = JSON.parse(req.responseText);
//Add the object data to your application.
}
}
//Send the request object to the sever
req.send()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment