Saturday, July 7, 2012

Use jQuery.ajax() without jQuery

Some time ago on on of the projects we needed to perform ajax calls, but can’t use jQuery (restriction came from customers). It was a bit tricky because we needed to use it with jsonp protocol and I didn’t want to implement all those things which are implemented in jQuery from scratch (including dynamic callback function which is passed in query string and executed when response is received).

If we can’t use jQuery.ajax(), we can try to copy only this part from jQuery and use it as standalone library (pure javascript without overriding ‘$’ symbol). It was actually not very hard. Just requires attention and perseverance. You need to copy jQuery.ajax() itself and all dependencies, including all methods and global variables which are used in them. It is defined as single object:

   1: var jQueryAjax = {
   2:  
   3:     noop: function() { },
   4:  
   5:     error: function(msg) {
   6:         throw msg;
   7:     },
   8:  
   9:     ...
  10: };

You can use it as general jQuery:

   1: jQueryAjax.ajax({
   2:     url: '/File/GetType',
   3:     datatype: 'json',
   4:     data: { filePath: val },
   5:     async: true,
   6:     success: function (res) {
   7:         $("#Type").val(res);
   8:     }
   9: });

I called file jQueryAjax-1.4.2.js (jQuery 1.4.2 was used) and uploaded it here. Decided to share it because it may be useful if you will need to do similar thing. It worked in our case (ajax calls with jsonp data type), but I’m not sure that it will work in all possible scenarios. Although I tried to be accurate when copy jQuery dependencies, it needs more testing. Anyway, hope that it will help someone.

No comments:

Post a Comment