working on it ...

Filters

Explore Public Snippets

Sort by

Found 272 snippets matching: xhr

    public by sTiLL-iLL @ SniPitz-KND  532553  3  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by sTiLL-iLL  348643  0  5  7

    XHR and fallback

    XHR and fallback: XHR.js
    // simple request with a fallback
    
    function getXHR() { 
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); 
      } 
      try { 
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
      }
      catch (err) { 
        try { 
          // fallback.
          return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch (err) { 
          alert('AJAX is not enabled.'); 
          return null;
        } 
      } 
    }
    
    

    public by HeathDernovich  156264  0  4  0

    XHR and fallback

    XHR and fallback: XHR.js
    // simple request with a fallback
    
    function getXHR() { 
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); 
      } 
      try { 
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
      }
      catch (err) { 
        try { 
          // fallback.
          return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch (err) { 
          alert('AJAX is not enabled.'); 
          return null;
        } 
      } 
    }
    
    

    public by sTiLL-iLL  2357  0  7  18

    XHR + a fallback...

    ...so krappy old browsers can do ajax to!
    // simple request with a fallback
    
    function getAjax() { 
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); 
      } 
      try { 
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
      }
      catch (err) { 
        try { 
          // fallback.
          return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch (err) { 
          alert('AJAX is not enabled.'); 
          return null;
        } 
      } 
    }

    public by sTiLL-iLL  1637  0  5  12

    XHR and fallback

    XHR and fallback: XHR.js
    // simple request with a fallback
    
    function getXHR() { 
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); 
      } 
      try { 
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
      }
      catch (err) { 
        try { 
          // fallback.
          return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch (err) { 
          alert('AJAX is not enabled.'); 
          return null;
        } 
      } 
    }
    
    

    public by kimurajin  1404  0  3  0

    add XHR2 progress events to jQuery.ajax

    add XHR2 progress events to jQuery.ajax: jquery.ajax.progress.js
    (function addXhrProgressEvent($) {
      var originalXhr = $.ajaxSettings.xhr;
      $.ajaxSetup({
        progress: function() { console.log("standard progress callback"); },
        xhr: function() {
          var req = originalXhr(), that = this;
          if (req) {
            if (typeof req.addEventListener == "function") {
              req.addEventListener("progress", function(evt) {
                that.progress(evt);
              },false);
            }
          }
          return req;
        }
      });
    })(jQuery);
    
    // usage:
    // note, if testing locally, size of file needs to be large enough
    // to allow time for events to fire
    
    $.ajax({
        url: "./json.js",
        type: "GET",
        dataType: "json",
        complete: function() { console.log("Completed."); },
        progress: function(evt) {
            if (evt.lengthComputable) {
                console.log("Loaded " + parseInt( (evt.loaded / evt.total * 100), 10) + "%");
            }
            else {
                console.log("Length not computable.");
            }
        }
    
    });
    
    

    external by Noitidart  137  0  2  0

    _ff-addon-snippet-xhrPromise - A function that does XHR wrapped up in a promise.

    _ff-addon-snippet-xhrPromise - A function that does XHR wrapped up in a promise.: _ff-addon-snippet-xhrPromise.js
    function xhr(aStr, aOptions={}) {
    	// currently only setup to support GET and POST
    	// does an async request
    	// aStr is either a string of a FileURI such as `OS.Path.toFileURI(OS.Path.join(OS.Constants.Path.desktopDir, 'test.png'));` or a URL such as `http://github.com/wet-boew/wet-boew/archive/master.zip`
    	// Returns a promise
    		// resolves with xhr object
    		// rejects with object holding property "xhr" which holds the xhr object
    	
    	/*** aOptions
    	{
    		aLoadFlags: flags, // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/NsIRequest#Constants
    		aTiemout: integer (ms)
    		isBackgroundReq: boolean, // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Non-standard_properties
    		aResponseType: string, // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Browser_Compatibility
    		aPostData: string
    	}
    	*/
    	
    	var aOptions_DEFAULT = {
    		aLoadFlags: Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING,
    		aPostData: null,
    		aResponseType: 'text',
    		isBackgroundReq: true, // If true, no load group is associated with the request, and security dialogs are prevented from being shown to the user
    		aTimeout: 0, // 0 means never timeout, value is in milliseconds
    		Headers: null
    	}
    	
    	for (var opt in aOptions_DEFAULT) {
    		if (!(opt in aOptions)) {
    			aOptions[opt] = aOptions_DEFAULT[opt];
    		}
    	}
    	
    	// Note: When using XMLHttpRequest to access a file:// URL the request.status is not properly set to 200 to indicate success. In such cases, request.readyState == 4, request.status == 0 and request.response will evaluate to true.
    	
    	var deferredMain_xhr = new Deferred();
    	console.log('here222');
    	let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
    
    	let handler = ev => {
    		evf(m => xhr.removeEventListener(m, handler, !1));
    
    		switch (ev.type) {
    			case 'load':
    			
    					if (xhr.readyState == 4) {
    						if (xhr.status == 200) {
    							deferredMain_xhr.resolve(xhr);
    						} else {
    							var rejObj = {
    								name: 'deferredMain_xhr.promise',
    								aReason: 'Load Not Success', // loaded but status is not success status
    								xhr: xhr,
    								message: xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']'
    							};
    							deferredMain_xhr.reject(rejObj);
    						}
    					} else if (xhr.readyState == 0) {
    						var uritest = Services.io.newURI(aStr, null, null);
    						if (uritest.schemeIs('file')) {
    							deferredMain_xhr.resolve(xhr);
    						} else {
    							var rejObj = {
    								name: 'deferredMain_xhr.promise',
    								aReason: 'Load Failed', // didnt even load
    								xhr: xhr,
    								message: xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']'
    							};
    							deferredMain_xhr.reject(rejObj);
    						}
    					}
    					
    				break;
    			case 'abort':
    			case 'error':
    			case 'timeout':
    				
    					var rejObj = {
    						name: 'deferredMain_xhr.promise',
    						aReason: ev.type[0].toUpperCase() + ev.type.substr(1),
    						xhr: xhr,
    						message: xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']'
    					};
    					deferredMain_xhr.reject(rejObj);
    				
    				break;
    			default:
    				var rejObj = {
    					name: 'deferredMain_xhr.promise',
    					aReason: 'Unknown',
    					xhr: xhr,
    					message: xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']'
    				};
    				deferredMain_xhr.reject(rejObj);
    		}
    	};
    
    	let evf = f => ['load', 'error', 'abort'].forEach(f);
    	evf(m => xhr.addEventListener(m, handler, false));
    
    	if (aOptions.isBackgroundReq) {
    		xhr.mozBackgroundRequest = true;
    	}
    	
    	if (aOptions.aTimeout) {
    		xhr.timeout
    	}
    	
    	var do_setHeaders = function() {
    		if (aOptions.Headers) {
    			for (var h in aOptions.Headers) {
    				xhr.setRequestHeader(h, aOptions.Headers[h]);
    			}
    		}
    	};
    	
    	if (aOptions.aPostData) {
    		xhr.open('POST', aStr, true);
    		do_setHeaders();
    		xhr.channel.loadFlags |= aOptions.aLoadFlags;
    		xhr.responseType = aOptions.aResponseType;
    		
    		/*
    		var aFormData = Cc['@mozilla.org/files/formdata;1'].createInstance(Ci.nsIDOMFormData);
    		for (var pd in aOptions.aPostData) {
    			aFormData.append(pd, aOptions.aPostData[pd]);
    		}
    		xhr.send(aFormData);
    		*/
    		var aPostStr = [];
    		for (var pd in aOptions.aPostData) {
    			aPostStr.push(pd + '=' + encodeURIComponent(aOptions.aPostData[pd])); // :todo: figure out if should encodeURIComponent `pd` also figure out if encodeURIComponent is the right way to do this
    		}
    		console.info('aPostStr:', aPostStr.join('&'));
    		xhr.send(aPostStr.join('&'));
    	} else {
    		xhr.open('GET', aStr, true);
    		do_setHeaders();
    		xhr.channel.loadFlags |= aOptions.aLoadFlags;
    		xhr.responseType = aOptions.aResponseType;
    		xhr.send(null);
    	}
    	
    	return deferredMain_xhr.promise;
    }
    
    

    external by Travis Hardiman  228  0  3  0

    IE11 has bad XHR that sends 0 bytes to upload a file when there is authentication, it stalls and never returns the 408 error

    IE11 has bad XHR that sends 0 bytes to upload a file when there is authentication, it stalls and never returns the 408 error: ie11.js
    // more info http://stackoverflow.com/questions/22542772/xmlhttprequest-upload-hangs-after-pause-between-uses
    // and possibly related: https://support.microsoft.com/en-us/kb/2962872/en-us?wa=wsignin1.0
    
    try {
    
    	// the someController.uploader is an Angular FileUploader: https://github.com/nervgh/angular-file-upload
    	// its url is set elsewhere to something like "/doc/upload/"
    	jQuery.ajax(someController.uploader.url, {
    		cache: false,
    		crossDomain: true,
    		method: "GET"
    	}).always(function callTheUploader () {
    		// this function is the one that actually uploads the file
    		someController.uploader.uploadAll();
    	});
    
    } catch (ex) {
    	if (window.console) {
    		window.console.log(ex);
    	}
    }
    
    

    external by geminiyellow  22  0  1  0

    xhrPool - extendable async xml requests pool, with sequent callbacks per xhr

    xhrPool - extendable async xml requests pool, with sequent callbacks per xhr: xhrpool.js
    // xhrPool - async xml requests pool, with sequent callbacks per xhr
    // 
    
        $.xhrPool = [];
        $.xhrPool.callbacks = [];
        $.xhrPool.starthandlers = []; 
    
    
     $.xhrPool.onEnd = function (name, obj, opts) {
    
            
            $.xhrPool = $.extend($.xhrPool, obj);
            $.xhrPool.callbacks.push({ 'fn': name, 'opts': opts });
    
        };
    
        $.xhrPool.onBegin = function (name, obj, opts) {
    
    
            $.xhrPool = $.extend($.xhrPool, obj);
            $.xhrPool.starthandlers.push({ 'fn': name, 'opts': opts });
    
        };
    
    
        $.xhrPool.flush = function () {
            $.xhrPool.callbacks = [];
            $.xhrPool.starthandlers = [];
            
        };
    
        $.xhrPool.abortAll = function () {
            $(this).each(function (idx, jqXhr) {
    
                jqXhr.abort();
            });
    
            $.xhrPool.length = 0;
        };
    
    
    
    //usage 
    
       if (!$.xhrPool.OnException)
            $.xhrPool.onEnd('OnException', { 'OnException': function (jx, opts, pool) {
    
                if (jx.statusText == "abort") {
    
                    $.xhrPool.empty();
    
                    jx.exception = 'true';
                  
                    jx.error = function () { };
                    jx.success = function () { };
                    jx = null;
                               
                }
    
            }
            }, null);
    
    
        if (!$.xhrPool.StopLoadingSpinner)
            $.xhrPool.onEnd('StopLoadingSpinner', { 'StopLoadingSpinner': function (jx, opts, pool) {
    
            //    $("#content").spin(false);
    
            }
            }, null);
    
    
        if (!$.xhrPool.StartLoadingSpinner)
            $.xhrPool.onBegin('StartLoadingSpinner', { 'StartLoadingSpinner': function (jx, opts, pool) {
    
              //  $("#content").spin("ajaxload");
    
            }
            }, null);
    
    
        
       
        $.ajaxSetup({
            beforeSend: function (jqXhr) {
    
                if (!$.xhrPool) return;
                
                $.xhrPool.push(jqXhr);
    
                $($.xhrPool.starthandlers).each(function (e) {
    
    
                    var fn = $.xhrPool.starthandlers[e].fn;
                    var opts = $.xhrPool.starthandlers[e].opts;
    
                    if (fn) {
    
                        var func = $.xhrPool[fn];
                        if (typeof (func) == 'function') func(jqXhr, $.extend(opts, $.xhrPool));
                    }
    
                });
    
            }
        });
    
      $(document).ajaxComplete(function (jxhr) {
            if (!$.xhrPool) return;
    
            var index = $.xhrPool.indexOf(jxhr);
            if (index > -1) {
                $.xhrPool.splice(index, 1);
            }
    
            $($.xhrPool.callbacks).each(function (e) {
    
    
                var fn = $.xhrPool.callbacks[e].fn;
                var opts = $.xhrPool.callbacks[e].opts;
    
                if (fn) {
    
    
                    var func = $.xhrPool[fn];
                    if (typeof (func) == 'function') func(jxhr, $.extend(opts, $.xhrPool));
                }
    
            });
    
          
          
        });
    
    
    
    

    external by Noitidart  319  0  3  0

    _ff-addon-snippet-xhrSync - Synchronus XHR request helper for use in Workers

    _ff-addon-snippet-xhrSync - Synchronus XHR request helper for use in Workers: _ff-addon-snippet-xhrSync.js
    function xhr(aUrlOrFileUri, aOptions={}) {
    	// console.error('in xhr!!! aUrlOrFileUri:', aUrlOrFileUri);
    	
    	// all requests are sync - as this is in a worker
    	var aOptionsDefaults = {
    		responseType: 'text',
    		timeout: 0, // integer, milliseconds, 0 means never timeout, value is in milliseconds
    		headers: null, // make it an object of key value pairs
    		method: 'GET', // string
    		data: null // make it whatever you want (formdata, null, etc), but follow the rules, like if aMethod is 'GET' then this must be null
    	};
    	validateOptionsObj(aOptions, aOptionsDefaults);
    	
    	var cRequest = new XMLHttpRequest();
    	
    	cRequest.open(aOptions.method, aUrlOrFileUri, false); // 3rd arg is false for synchronus
    	
    	if (aOptions.headers) {
    		for (var h in aOptions.headers) {
    			cRequest.setRequestHeader(h, aOptions.headers[h]);
    		}
    	}
    	
    	cRequest.responseType = aOptions.responseType;
    	cRequest.send(aOptions.data);
    	
    	// console.log('response:', cRequest.response);
    	
    	// console.error('done xhr!!!');
    	return cRequest;
    }
    
    
    • Public Snippets
    • Channels Snippets