-
Notifications
You must be signed in to change notification settings - Fork 0
Post Ajax
Rayhan Uddin edited this page Jun 2, 2017
·
3 revisions
Ajax with Plain Javascript 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);
});