How to write an AJAX method

JavaScript polyfill, by , Wednesday, June 18th, 2014

If you do any kind of serious web development you will with certainty encounter having to do AJAX calls. Using a library like jQuery, this is made quite straight forward, but as in so many other cases, knowing how to solve the task without this kind of helping tools, can be both useful and educational. So in this short article I will present a simple AJAX function written in Vanilla JavaScript.

Before we dive into the code, I would like to point out, that this is not an exhaustive AJAX function, but and educational example of how you could go about implementing one, were you to write a small simple library or add this functionality to some existing code base. With that said, lets look at the code;

  1. var ajax = function (settings) {
  2. var xmlhttp = (function () {
  3. if (window.XMLHttpRequest) {
  4. try {
  5. return new window.XMLHttpRequest();
  6. } catch (ignore) {}
  7. } else if (window.ActiveXObject) {
  8. try {
  9. return new window.ActiveXObject("Microsoft.XMLHTTP");
  10. } catch (ignore) {}
  11. }
  12. }()),
  13. responseMap = {
  14. 'text' : 'responseText',
  15. 'xml' : 'responseXML'
  16. },
  17. response = (settings.response && responseMap[settings.response]) ? responseMap[settings.response] : responseMap.text,
  18. method = (function () {
  19. var requestType = {};
  20. if (settings.method && settings.method.toUpperCase() === 'POST') {
  21. requestType.type = settings.method;
  22. requestType.typePost = true;
  23. } else {
  24. requestType.type = 'GET';
  25. requestType.typePost = false;
  26. }
  27. return requestType;
  28. }()),
  29. query = (settings.query && method.typePost) ? settings.query : null;
  30.  
  31. if (xmlhttp) {
  32. xmlhttp.open(method.type, settings.url, true);
  33. xmlhttp.onreadystatechange = function () {
  34. try {
  35. if (xmlhttp.readyState === 4) {
  36. if (xmlhttp.status >= 200 && xmlhttp.status <= 206) {
  37. if (settings.callback) {
  38. settings.callback(xmlhttp[response]);
  39. }
  40. }
  41. }
  42. } catch (ignore) {}
  43. };
  44.  
  45. if (method.typePost) {
  46. xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  47. } else if (!settings.cache) {
  48. xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
  49. }
  50. xmlhttp.send(query);
  51. }
  52. };

The function expects the following parameters:

  • response: String, 'responseText' or 'responseXML', default is 'responseText.
  • method: String, 'GET' or 'POST', default is 'GET'
  • query: String, POST query string, ignored when GET
  • url: String, URL to file
  • cache: Boolean, prevent browser cache for GET, default is false.

This implementation should work in all modern browsers and even in some ancient fossils still roaming the web.