Skip to content

Instantly share code, notes, and snippets.

@avtarnanrey
Created November 28, 2017 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avtarnanrey/cb5aad88d5294d604681956f15f61d35 to your computer and use it in GitHub Desktop.
Save avtarnanrey/cb5aad88d5294d604681956f15f61d35 to your computer and use it in GitHub Desktop.
AJAX calls using vanilla JavaScript and jQuery
(function(){
var httpRequest, root;
root = 'https://jsonplaceholder.typicode.com'; // URL for JSON data
document.querySelector('.ajaxButton').addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if(!httpRequest){
console.log('Cannot create XMLHTTP isntance');
return fales;
}
httpRequest.onreadystatechange = consoleContents;
httpRequest.open('GET', root + '/posts'); // GET, POST..
httpRequest.send();
}
function consoleContents(){
if(httpRequest.readyState === XMLHttpRequest.DONE){
if(httpRequest.status === 200){
console.log(httpRequest.responseText); // responseText is your result.
} else {
console.log('There was a problem with the request');
}
}
}
})();
/******
***** jQuery Method *****
*****/
function getPost(){
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
success: function(data){
console.log(data);
},
error: function() {
console.log('Error');
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment