Skip to content

Instantly share code, notes, and snippets.

@davidalves1
Last active June 15, 2022 21:09
Show Gist options
  • Save davidalves1/efee52fd2c498f546d3b2b6d1b424254 to your computer and use it in GitHub Desktop.
Save davidalves1/efee52fd2c498f546d3b2b6d1b424254 to your computer and use it in GitHub Desktop.
Make a ajax request with JavaScript
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