Skip to content

Instantly share code, notes, and snippets.

@iworkforthem
Created December 24, 2016 11:43
Show Gist options
  • Save iworkforthem/86c49909eaaaf82c9179c8b95e660008 to your computer and use it in GitHub Desktop.
Save iworkforthem/86c49909eaaaf82c9179c8b95e660008 to your computer and use it in GitHub Desktop.
javascript form post.
function postAjax(url, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
// example request
postAjax('http://foo.bar/', 'p1=1&p2=Hello+World', function(data){ console.log(data); });
// example request with data object
postAjax('http://foo.bar/', { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment