Skip to content

Instantly share code, notes, and snippets.

@chriswrightdesign
Created January 18, 2014 03:50
Show Gist options
  • Save chriswrightdesign/8485927 to your computer and use it in GitHub Desktop.
Save chriswrightdesign/8485927 to your computer and use it in GitHub Desktop.
Ajax sans jQuery (i think the last time I did this was 2006 or 2007) source: www.aaron-powell.com/posts/2013-08-02-ajax-without-jquery.html
//instance
var xhr = new XMLHttpRequest();
//open the request with method
xhr.open('get', '/foo');
//dom events- load, progress, error
//progress listen for and inform user of status if it takes a long time
xhr.addEventListener('load', function(e) {
//handle success
}, false);
xhr.send(); // sends the request
//responses
xhr.addEventListener('load', function(e){
var o = JSON.parse(xhr.responseText); // or e.responseText;
}, false);
//how about posting
xhr.open('POST', '/foo');
var data = new FormData();
data.append('name', 'Chris');
xhr.send(data);
//name is the key of a form value and Chris is the value
//in asp.net this would be httpRequest.Form object. Express.js it'll be request.form
//set the header so the server knows it's json
xhr.setRequestHeader('Content-Type', 'application/json');
//set the content length so the server knows how much data to expect
xhr.setRequestHeader('Content-Length', JSON.stringify(data).length);
//finally when you send you send up a json string not the object
xhr.send(JSON.stringify(data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment