ajax request with callback function using native JavaScript
The function sends ajax request with
vanilla JavaScript
and calls the
callback function
if the third parameter's type is
function
function ajax(url, methodType, callback){
    var xhr = new XMLHttpRequest();
    xhr.open(methodType, url, true);
    xhr.send();
    xhr.onreadystatechange = function(){
        if (xhr.readyState === 4 && xhr.status === 200){
            if (typeof callback === "function") {
                callback(xhr.responseText);
            }
        }
    }
}
Example of calling the above method
ajax(url, 'GET', function(resp) {
    console.log(resp);
})
by Valeri Tandilashvili
4 years ago
JavaScript
ajax
2
Pro tip: use ```triple backticks around text``` to write in code fences