What is AJAX and Why Should I Care?
Video
JavaScript Notes
JavaScript
// AJAX = Asynchronous JavaScript and XML
// none of these examples do proper error handling of
// nasty http status codes or
// invalid data types – text, xml, json, etc
// ***************************************************
// Old version of AJAX
var xhr = new XMLHttpRequest( );
xhr.open('GET', uri, true); // true here means asynchronous call (user can still interact with site, while waiting for request to come back)
xhr.addEventListener('load', function(response){
//handle the response from the server
var data = response.responseText; // responseXML
var json = JSON.parse(data); // JSON object
console.log('XMLHttpRequest : ', data) ;
});
xhr.addEventListener('error', function(err){
//error handling network request
})
xhr.send(null);
//***************************************************
// New version of AJAX
fetch(uri)
.then(function(response){
return response.json( );
})
.then(function(data){
console.log(data);
});
.catch(function(err){
// error handling network request
})
Feedback
Submit and view feedback