Created
October 18, 2015 19:44
-
-
Save jasdeepkhalsa/15d1a55c0b2e140e61d3 to your computer and use it in GitHub Desktop.
Simple cross-browser AJAX method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define our own ajax method which uses XMLHttpRequest to fetch data from our Node.js app and OMDBapi.com | |
function ajax(url, method, callback, data, header) { | |
try { | |
var req = new(XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0'); // Does XMLHttpRequest exist? If not, it's probably an older version of Internet Explorer | |
req.open(method, url, true); // the method is either GET or POST in our case, the url which we want to call to get data from and TRUE to make it an asynchronous request | |
if (header) { | |
req.setRequestHeader("Content-type", header); // Set a custom header | |
} | |
req.onreadystatechange = function () { | |
req.readyState > 3 && callback && callback(req.responseText, req); // When the response comes back call the callback function | |
}; | |
if (data) { | |
req.send(data) // Send with data | |
} else { | |
req.send(); // Send without data | |
} | |
} catch (e) { | |
window.console && console.error(e); // If there is an error, show it in the browser's F12 console | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment