There are many ways to make an AJAX call back to your server from the clients browser.  But what is the best way to do this using only JavaScript.  Using just JavaScript will insure that it will work in all browsers, and will remove that dependency on other libraries or frameworks.

This sample code shows you how to setup your base class, and how to call it from other objects.

//Base Class
function request(method, url, data, callback) {
   if (window.XMLHttpRequest) {
      var req = new XMLHttpRequest();
   } else {
      var req = new ActiveXObject('Microsoft.XMLHTTP');
   }
   if (method === 'GET' && typeof data === 'string') {
      url += '?' + data;
   }
       req.open(method, url, true);
     if (method === 'POST' && typeof data === 'string') {
      req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   }      req.onreadystatechange = function() {
      if (req.readyState === 4 && req.status === 200) {
         var contentType = req.getResponseHeader('Content-type');
         if (contentType === 'application/json') {
            callback(JSON.parse(req.responseText));
         } else {
            callback(req.responseText);
         }       } else if (req.readyState === 4) {
         throw new Error('XHR Request Failed: ' + req.status);
      }
   };
   req.send((typeof data === 'string' && method === 'POST') ? data : null); return req;
}

//Alias for GET function
function get(url, data, callback) {
   return request('GET', url, data, callback);
}

//Alias for POST function
function post(url, data, callback) {
   return request('POST', url, data, callback);
}

//Usage
request('GET', '/ajax', 'foo-bar', function(body) {
   console.log(body);
});

//With Alias
get('test.aspx', 'foo=bar', function(time) {
   document.getElementById('time').innerHTML = time;
});

Categories


Most Visited