Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Created October 18, 2015 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdeepkhalsa/15d1a55c0b2e140e61d3 to your computer and use it in GitHub Desktop.
Save jasdeepkhalsa/15d1a55c0b2e140e61d3 to your computer and use it in GitHub Desktop.
Simple cross-browser AJAX method
// 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