Last active
June 15, 2022 21:09
-
-
Save davidalves1/efee52fd2c498f546d3b2b6d1b424254 to your computer and use it in GitHub Desktop.
Make a ajax request with JavaScript
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
var ajax = function(config) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(config.method, config.url, true); | |
xhr.setRequestHeader('Content-Type', 'application/json'); | |
xhr.onload = function (e) { | |
if (xhr.readyState === 4) { | |
config.callback({ | |
status: xhr.status, | |
response: xhr.responseText | |
}); | |
} | |
}; | |
xhr.onerror = function (e) { | |
config.callback({ | |
status: xhr.statusText, | |
response: xhr.statusText | |
}); | |
}; | |
xhr.send(config.data); | |
}; | |
function handleResponse(data) { | |
if (data.status === 200) | |
console.log('Yeah! Sucesso'); | |
else | |
console.log('Oh no! Error ' + data.status); | |
} | |
var config = { | |
method: 'GET', | |
url: 'https://api.github.com/users/davidalves1', | |
data: {}, | |
callback: handleResponse | |
} | |
ajax(config); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment