AJAX with native JavaScript

Consider a few examples of working with AJAX with native JavaScript. Functions are written with ECMAScript-2015 syntax

The function for the GET method:

let ajaxGet = (url, callback) => {
    let xhr = new XMLHttpRequest();
     
     xhr.onreadystatechange = () => {
        if (xhr.readyState == 4){
            if(xhr.status == 200){
                alert( xhr.responseText );
                callback();
            } else {
                // if error
                alert(xhr.statusText);
            }
        }
    };
    xhr.open('GET', url, true);
    xhr.send(null);
};

The function for the POST method. The data to be sent to the server accepts both the string and the object.

let ajaxPost = options => {
 
    /* an example
     * options = {
     *      data: 'a=1&b=word&c=name',
     *       url: 'test.php',
     *       cb: function(){
     *          alert('test');
     *       }
     *  }
     */
    let sendstr = '',
        xhr = new XMLHttpRequest();
 
    if (typeof options.data == 'object') {
        let lastEl = Object.keys(options.data).length - 1;
        let count = 0;
        for (var k in options.data) {
            if (options.data.hasOwnProperty(k)) {
                sendstr += k + '=' + options.data[k] + (count != lastEl ? '&' : '');
                count++;
            }
        }
    } else {
        sendstr = options.data;
    }
    xhr.open('POST', options.url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(sendstr);
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
            if(xhr.status == 200){
                alert(xhr.responseText);
                if (options.cb) {
                    options.cb();
                }
            }else {
                // else error
                alert(xhr.statusText);
            }
        }
    };
};

To support older versions of Internet Explorer, you had to write another helper function, something like

function getXmlHttpRequest(){
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        return null;
    }
}

Comments

Popular posts from this blog

Typical gulpfile.js

JavaScript Inheritance and Classes

Swipe events on touch devices