data-store.php

Basic data store utility -- unfinished
git clone git://git.finwo.net/lib/data-store.php
Log | Files | Refs

ajax.js (4101B)


      1 (function(exports) {
      2 
      3   var factories = [
      4     function () {return new XMLHttpRequest()},
      5     function () {return new ActiveXObject("Msxml2.XMLHTTP")},
      6     function () {return new ActiveXObject("Msxml3.XMLHTTP")},
      7     function () {return new ActiveXObject("Microsoft.XMLHTTP")}
      8   ];
      9 
     10   function httpObject() {
     11     var xmlhttp = false;
     12     factories.forEach(function(factory) {
     13       try {
     14         xmlhttp = xmlhttp || factory();
     15       } catch(e) {
     16         return;
     17       }
     18     });
     19     return xmlhttp;
     20   }
     21 
     22   function serializeObject(obj,prefix) {
     23     var str = [], p;
     24     for(p in obj) {
     25       if (obj.hasOwnProperty(p)) {
     26         var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
     27         str.push((v !== null && typeof v === "object") ?
     28           serializeObject(v, k) :
     29         encodeURIComponent(k) + "=" + encodeURIComponent(v));
     30       }
     31     }
     32     return str.join("&");
     33   }
     34 
     35   function SimplePromise()
     36   {
     37     var self  = this,
     38         queue = [],
     39         doneFunction = null,
     40         failFunction = function(e){throw e;},
     41         started      = false,
     42         running      = false;
     43     this.then = function(callback) {
     44       queue.push(callback);
     45       if(started&&!running) self.run();
     46       return self;
     47     };
     48     this.fail = function(callback) {
     49       failFunction = callback;
     50       if(started&&!running) self.run();
     51       return self;
     52     };
     53     this.done = function(callback) {
     54       doneFunction = callback;
     55       if(started&&!running) self.run();
     56       return self;
     57     };
     58     this.start = function(callback) {
     59       queue.push(callback);
     60       self.run();
     61       return self;
     62     };
     63     this.run = function(data, done) {
     64       started = true;
     65       running = true;
     66       var returnValue;
     67       if(this!=self) {
     68         done = this;
     69       }
     70       while(queue.length) {
     71         var func = queue.shift();
     72         if (!func) {
     73           running = false;
     74           if (typeof done === 'function')         return done(data);
     75           if (typeof doneFunction === 'function') return doneFunction(data);
     76           return data;
     77         }
     78         try {
     79           returnValue = null;
     80           returnValue = func.call(null, data, self.run.bind(done), failFunction);
     81         } catch(e) {
     82           running = false;
     83           if (typeof failFunction === 'function') return failFunction(e, data);
     84           throw e;
     85         }
     86         if(!returnValue) {
     87           return;
     88         }
     89       }
     90       running = false;
     91       if (typeof done === 'function')         return done(data);
     92       if (typeof doneFunction === 'function') return doneFunction(data);
     93       return data;
     94     };
     95   }
     96 
     97   function ajax( uri, options ) {
     98     options = options || {};
     99 
    100     var method  = (options.method || 'GET').toUpperCase(),
    101         data    = options.data || {},
    102         promise = new SimplePromise();
    103 
    104     var req = httpObject();
    105     if (!req) return;
    106 
    107     // Insert data?
    108     if(Object.keys(data).length) {
    109       var serializedData = serializeObject(data);
    110       switch(method) {
    111         case 'GET':
    112           uri += ((uri.indexOf('?')===false) ? '?' : '&') + serializedData;
    113           data = {};
    114           break;
    115         case 'POST':
    116           req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    117           break;
    118       }
    119     }
    120 
    121     // Let's start
    122     req.open(method, uri, true);
    123 
    124     return promise.start(function(d, resolve, reject) {
    125       req.onreadystatechange = function() {
    126         if(req.readyState!=4) return;
    127         if(req.status<200||req.status>=300) {
    128           reject('Invalid response');
    129         }
    130         var receivedData = req.responseText;
    131         try {
    132           receivedData = JSON.parse(receivedData);
    133         } catch(e) {
    134           // Nothing to worry about
    135         }
    136         resolve(receivedData);
    137       };
    138       req.send(data);
    139     });
    140   }
    141 
    142   // Export our freshly created plugin
    143   exports.ajax = ajax;
    144   if (typeof define === 'function' && define.amd) {
    145     define('ajax', function() {
    146       return ajax;
    147     })
    148   }
    149 
    150   // Attach to window as well
    151   if (typeof window !== 'undefined') {
    152     window.ajax = ajax;
    153   }
    154 
    155 })(typeof exports === 'object' && exports || this);