How to make an AJAX call without jQuery?
With "vanilla" JavaScript:
<script type="text/javascript">function loadXMLDoc() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4 if (xmlhttp.status == 200) { document.getElementById("myDiv").innerHTML = xmlhttp.responseText; } else if (xmlhttp.status == 400) { alert('There was an error 400'); } else { alert('something else other than 200 was returned'); } } }; xmlhttp.open("GET", "ajax_info.txt", true); xmlhttp.send();}</script>
With jQuery:
$.ajax({ url: "test.html", context: document.body, success: function(){ $(this).addClass("done"); }});
Using the following snippet you can do similar things pretty easily, like this:
ajax.get('/test.php', {foo: 'bar'}, function() {});
Here is the snippet:
var ajax = {};ajax.x = function () { if (typeof XMLHttpRequest !== 'undefined') { return new XMLHttpRequest(); } var versions = [ "MSXML2.XmlHttp.6.0", "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ]; var xhr; for (var i = 0; i < versions.length; i++) { try { xhr = new ActiveXObject(versions[i]); break; } catch (e) { } } return xhr;};ajax.send = function (url, callback, method, data, async) { if (async === undefined) { async = true; } var x = ajax.x(); x.open(method, url, async); x.onreadystatechange = function () { if (x.readyState == 4) { callback(x.responseText) } }; if (method == 'POST') { x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } x.send(data)};ajax.get = function (url, data, callback, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)};ajax.post = function (url, data, callback, async) { var query = []; for (var key in data) { query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } ajax.send(url, callback, 'POST', query.join('&'), async)};
I know this is a fairly old question, but there is now a nicer API available natively in newer browsers. The fetch()
method allow you to make web requests.For example, to request some json from /get-data
:
var opts = { method: 'GET', headers: {}};fetch('/get-data', opts).then(function (response) { return response.json();}).then(function (body) { //doSomething with body;});
See here for more details.