Created
December 24, 2016 11:43
-
-
Save iworkforthem/86c49909eaaaf82c9179c8b95e660008 to your computer and use it in GitHub Desktop.
javascript form post.
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 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