Created
November 28, 2017 20:47
-
-
Save avtarnanrey/cb5aad88d5294d604681956f15f61d35 to your computer and use it in GitHub Desktop.
AJAX calls using vanilla JavaScript and 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
(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