Web Dev Ramblings

Fetching data from your server without jQuery

Published Monday, June 13, 2016

The ability to load content from the server without forcing a page refresh is useful in so many ways. You can use it to dynamically load parts of the page, snippets of script or styles and more.

Sadly it is not uncommon to see people including a large JavaScript library like jQuery just to access this type of capability, when you actually only need a couple of lines of code (165 bytes):

function ServerRequest(url, onload) { var xhr = new XMLHttpRequest(); xhr.onload = function () { onload(xhr.responseText); } xhr.open('GET', url); xhr.send(); }
Or minimized 117 bytes:
function ServerRequest(e,n){var t=new XMLHttpRequest;t.onload=function(){n(t.responseText)},t.open("GET",e),t.send()}

And to actually do something useful, like update a div with content from the server:

ServerRequest('/data_on_my_server.html', function(s) { document.getElementById('someDiv').innerHTML = s; });

I need a little more than that

If you want to get ever so slightly more fancy you can use something more like this, which allows for both GET and POST requests, an makes the onload handler optional and adds an optional error handler and the ability to overwrite the request verb (499 bytes):

function ServerRequest(o) { var xhr = new XMLHttpRequest(); if (o.onload) { xhr.onload = function () { o.response = xhr.responseText; o.onload(o); } } if (o.onerror) { xhr.onerror = function () { o.onerror(o); } } var data = ""; for (a in o.data) { data += ((data.length)? '&' : '') + a + "=" + encodeURIComponent(o.data[a]); } xhr.open((o.verb) ? o.verb : (o.data) ? 'POST' : 'GET', o.url); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); xhr.send(data); }
Or minimized (396 bytes):
function ServerRequest(e){var n=new XMLHttpRequest;e.onload&&(n.onload=function(){e.response=n.responseText,e.onload(e)}),e.onerror&&(n.onerror=function(){e.onerror(e)});var o="";for(a in e.data)o+=(o.length?"&":"")+a+"="+encodeURIComponent(e.data[a]);n.open(e.verb?e.verb:e.data?"POST":"GET",e.url),n.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"),n.send(o)}
To use it, you'd use something like this:
ServerRequest({ url: '/data_on_my_server/', onload: FunctionToCallWhenDataIsLoaded });
Or if you need to post some data to your server, like so:
ServerRequest({ url: '/post_to_here/', data: { FirstName: 'Hello', LastName: 'World' }, onload: FunctionToCallWhenPostCompletes });

This is the code we actually use on this page, and one big benefit is that it allows us to tack on any related context we want to the request object, which can be very useful if you have the need for more complicated response handlers.

Why not just use XMLHttpRequest directly?

That is certainly a reasonable way to do it. Since most code I've written tends to use it in many places, and rarely to load XML, I prefer this simpler one line use. Calling it ServerRequest or RequestFromServer or something like that just feels more natural as well.

Browser Support

These scripts require XMLHTTPRequest level 2 which is supported by all modern browsers.