Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple, cross-browser Javascript POST/GET xhr request object. Supports request data and proper AJAX headers.
/**
* IE 5.5+, Firefox, Opera, Chrome, Safari XHR object
*
* @param string url
* @param object callback
* @param mixed data
* @param null x
*/
function ajax(url, callback, data, x) {
try {
x = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
x.open(data ? 'POST' : 'GET', url, 1);
x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onreadystatechange = function () {
x.readyState > 3 && callback && callback(x.responseText, x);
};
x.send(data)
} catch (e) {
window.console && console.log(e);
}
};
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// https://gist.github.com/jed/993585
// https://gist.github.com/Fluidbyte/5082377
// https://github.com/Xeoncross/kb_javascript_framework/blob/master/kB.js#L30
// https://gist.github.com/iwek/5599777
// http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx#_id
// @todo look into lengthComputable for xhr.upload browsers
// http://stackoverflow.com/questions/11127654/why-is-progressevent-lengthcomputable-false
// http://stackoverflow.com/questions/10956574/why-might-xmlhttprequest-progressevent-lengthcomputable-be-false
// https://github.com/ForbesLindesay/ajax/blob/master/index.js
/**
* IE 5.5+, Firefox, Opera, Chrome, Safari XHR object
*
* @param string url
* @param object callback
* @param mixed data
* @param null x
*/
var ajax(url, callback, data, cache) {
// Must encode data
if(data && typeof(data) === 'object') {
var y = '', e = encodeURIComponent;
for (x in data) {
y += '&' + e(x) + '=' + e(data[x]);
}
data = y.slice(1) + (! cache ? '&_t=' + new Date : '');
}
try {
var x = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
x.open(data ? 'POST' : 'GET', url, 1);
x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onreadystatechange = function () {
x.readyState > 3 && callback && callback(x.responseText, x);
};
x.send(data)
} catch (e) {
window.console && console.log(e);
}
};
ajax.uriEncode = function(o) {
var x, y = '', e = encodeURIComponent;
for (x in o) y += '&' + e(x) + '=' + e(o[x]);
return y.slice(1);
};
ajax.collect = (a, f) {
var n = [];
for (var i = 0; i < a.length; i++) {
var v = f(a[i]);
if (v != null) n.push(v);
}
return n;
};
ajax.serialize = function (f) {
function g(n) {
return f.getElementsByTagName(n);
};
var nv = function (e) {
if (e.name) return encodeURIComponent(e.name) + '=' + encodeURIComponent(e.value);
};
var i = collect(g('input'), function (i) {
if ((i.type != 'radio' && i.type != 'checkbox') || i.checked) return nv(i);
});
var s = collect(g('select'), nv);
var t = collect(g('textarea'), nv);
return i.concat(s).concat(t).join('&');
};
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// https://gist.github.com/jed/993585
// https://gist.github.com/Fluidbyte/5082377
// https://github.com/Xeoncross/kb_javascript_framework/blob/master/kB.js#L30
// https://gist.github.com/iwek/5599777
// http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx#_id
// @todo look into lengthComputable for xhr.upload browsers
// http://stackoverflow.com/questions/11127654/why-is-progressevent-lengthcomputable-false
// http://stackoverflow.com/questions/10956574/why-might-xmlhttprequest-progressevent-lengthcomputable-be-false
@chejazi

This comment has been minimized.

Copy link

commented Nov 8, 2014

This is great - thanks for contributing!

@MattMcFarland

This comment has been minimized.

Copy link

commented Jun 5, 2015

This is badass

@eduardoinnorway

This comment has been minimized.

Copy link

commented Nov 16, 2015

I like, just one thing, "data ? 'POST' : 'GET'" this will always become POST. Do the condiction check before instead, and set for example data to GET as default if not POST or GET is set, or just do some error handling about wrong type. I will modify and use, thanks.

@leolovenet

This comment has been minimized.

Copy link

commented Mar 27, 2016

If you want to use a synchronization request,
can not write
x.open(data ? 'POST' : 'GET', url, 0);
this will not work under > ie8 , must be
x.open(data ? 'POST' : 'GET', url, false);

@ephraimtabackman

This comment has been minimized.

Copy link

commented Jun 2, 2016

@eduardoinnorway: I think you misunderstood the meaning of the data parameter. It is an optional Object of POST data. If it is undefined, the method will be GET.

@CestDiego

This comment has been minimized.

Copy link

commented Sep 12, 2016

but what if I want to make a get request with data? I would expect data would be serialized and passed as a query parameter on the url.

@nicdex

This comment has been minimized.

Copy link

commented May 2, 2017

Why the x parameter???

@timruffles

This comment has been minimized.

Copy link

commented Jul 17, 2017

@Xeoncross would you mind popping a license on this?

@notflip

This comment has been minimized.

Copy link

commented Nov 25, 2017

What's the testing.ajax.js for?

@Download

This comment has been minimized.

Copy link

commented Dec 20, 2018

Why the x parameter???

@nicdex It is a trick. It is just shorter to add a parameter than to write 'var x'. So it saves a few bytes at the cost of readability.

@JamesTheHacker

This comment has been minimized.

Copy link

commented Apr 16, 2019

It's a nice trick if the intent is to golf the code but for readability it throws one off for a moment. Nice code though. I've "borrowed" your code and linked back to this in source code :)

@MDReal32

This comment has been minimized.

Copy link

commented May 9, 2019

Thanks man helps to me. To modify js ajax Request

@herdianf

This comment has been minimized.

Copy link

commented Aug 1, 2019

I will go with
x.open(typeof data != 'undefined' ? 'POST' : 'GET', url, 1);
since sometime I need to send a POST with empty body

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.