Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript pure ajax promise

function getRequest(url) {
    return makeRequest('GET', url);
}

function postRequest(url, data) {
    return makeRequest('POST', url, data);
}

function makeRequest(method, url, data) {
    return new Promise(
        function(resolve, reject) {
            var http = new XMLHttpRequest();
            http.open(method, url);
            http.onload = function() {
                if (this.status >= 200 && this.status < 300) {
                    var response = http.response;
                    try {
                        response = JSON.parse(response);
                        resolve(response);
                    } catch (error) {
                        reject({
                            status: this.status,
                            statusText: error
                        });
                    }

                } else {
                    reject({
                        status: this.status,
                        statusText: http.statusText
                    });
                }
            };
            http.onerror = function() {
                reject({
                    status: this.status,
                    statusText: http.statusText
                });
            };

            if (method === 'POST') {
                data = data || new FormData();
                http.send((data));
            } else http.send();
        }
    );
}
Source by www.taniarascia.com #
 
PREVIOUS NEXT
Tagged: #javascript #pure #ajax #promise
ADD COMMENT
Topic
Name
6+9 =