HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Raw JS AJAX method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rawajaxmethod

Problem

I built this as a simple example of using raw JS to perform a simple GET request with a data callback.

Suggestions on how this could be improved in any way, while keeping it simple, would be much appreciated.

JS:

/*jslint unparam: true, white: true */

var app = (function() {
    "use strict";

    return {
        ajax: function(url, callback) {

            var xmlhttp = new window.XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                var data;

                if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                    data = xmlhttp.responseText;

                    if(typeof callback === 'function') {
                        callback(data);
                    }
                }
            };

            xmlhttp.open('GET', url, true);
            xmlhttp.send();
        }
    };

}());


Example usage:

app.ajax('file.json', function(data) {
    data = JSON.parse(data);
    console.log(data.name);
});

Solution

From a once over:

  • There should be a way to handle errors, this is only good for sunny day scenarios



  • It would be more useful if you also passed the xmlhttp object to the callback : callback(data, xmlhttp);



  • As stated by Vogel612, it wont work for some versions of IE, it's not hard to add support for those



  • There is no need at all to declare data, you can pass xmlhttp.responseText; straight to callback, it would make the code tighter



  • A comment as to what 4 and 200 stand for could be useful for the unaware reader



Other than that, looks good.

Context

StackExchange Code Review Q#44742, answer score: 3

Revisions (0)

No revisions yet.