1 /* jQuery ajax stream plugin
3 * Copyright (C) 2009 Chris Tarquini
4 * Licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License (http://creativecommons.org/licenses/by-sa/3.0/)
5 * Permissions beyond the scope of this license may be available by contacting petros000[at]hotmail.com.
10 // Save the original AJAX function
11 var ajax_old = $.ajax;
13 var post_old = $.post;
16 $.ajaxSetup({stream: false,pollInterval: 500/*, onDataRecieved: function(){}*/ });
17 $.enableAjaxStream = function(enable)
19 if(typeof enable == 'undefined') enable = !active;
30 $.get = ajax_get_stream;
31 $.post = ajax_post_stream;
36 var ajax_stream = $.ajax = function(options)
38 //copied from original ajax function
39 options = jQuery.extend(true, options, jQuery.extend(true, {}, jQuery.ajaxSettings, options));
47 var hook = function(xhr)
52 var fix = function(){ check('stream'); };// fixes weird bug with random numbers as arg
53 var checkagain = function(){if(!done) timer = setTimeout(fix,options.pollInterval);}
54 var check = function(status)
56 if(typeof status == 'undefined') status = "stream";
57 if(xmlhttp.status < 3) return; //only get the latest packet if data has been sent
58 var text = xmlhttp.responseText;
59 if(status == 'stream') //if we arent streaming then just flush the buffer
61 if(text.length <= lastlen) { checkagain(); return;}
62 lastlength = text.length;
63 if(offset == text.length) { checkagain(); return;}
65 var pkt = text.substr(offset);
67 if($.isFunction(options.OnDataRecieved))
69 options.OnDataRecieved(pkt, status, xmlhttp.responseText, xmlhttp);
71 if(xmlhttp.status != 4)
74 var complete = function(xhr,s)
76 clearTimeout(timer);//done..stop polling
81 // If the complete callback is set create a new callback that calls the users and outs
82 if($.isFunction(options.success))
84 var oc = options.success;
85 options.success = function(xhr,s){ complete(xhr,s); oc(xhr,s);};
88 else options.success = complete;
89 // Set up our hook on the beforeSend
90 if($.isFunction(options.beforeSend))
92 var obs = options.beforeSend;
93 options.beforeSend = function(xhr){ obs(xhr); hook(xhr);};
95 else options.beforeSend = hook;
101 var ajax_get_stream = $.get = function(url,data,callback,type,stream)
103 if($.isFunction(data))
105 var orgcb = callback;
107 if($.isFunction(orgcb))
113 if($.isFunction(type))
118 var dostream = $.isFunction(stream);
126 OnDataRecieved: stream
131 var ajax_post_stream = $.post = function(url,data,callback,type,stream)
133 if($.isFunction(data))
135 var orgcb = callback;
138 if($.isFunction(type))
143 var dostream = $.isFunction(stream);
151 OnDataRecieved: stream