$.fn.formValues;
[jquery.git] / ajax / ajax.js
1 // AJAX Plugin
2 // Docs Here:
3 // http://jquery.com/docs/ajax/
4
5 if ( typeof XMLHttpRequest == 'undefined' && typeof window.ActiveXObject == 'function') {
6         XMLHttpRequest = function() {
7                 return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') >= 0) ?
8                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP");
9         };
10 }
11
12 // Counter for holding the active query's
13 $.xmlActive=0;
14
15 $.xml = function( type, url, data, ret ) {
16         var xml = new XMLHttpRequest();
17
18         if ( xml ) {
19                 // Open the socket
20                 xml.open(type || "GET", url, true);
21                 if ( data )
22                         xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
23
24                 // Set header so calling script knows that it's an XMLHttpRequest
25                 xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
26
27                 /* Force "Connection: close" for Mozilla browsers to work around
28                  * a bug where XMLHttpReqeuest sends an incorrect Content-length
29                  * header. See Mozilla Bugzilla #246651.
30                  */
31                 if ( xml.overrideMimeType )
32                         xml.setRequestHeader('Connection', 'close');
33
34                 xml.onreadystatechange = function() {
35                         // Socket is openend
36                         if ( xml.readyState == 1 ) {
37                                 // Increase counter
38                                 $.xmlActive++;
39
40                                 // Show loader if needed
41                                 if ( ($.xmlActive >= 1) && ($.xmlCreate) )
42                                         $.xmlCreate();
43                         }
44
45                         // Socket is closed and data is available
46                         if ( xml.readyState == 4 ) {
47                                 // Decrease counter
48                                 $.xmlActive--;
49
50                                 // Hide loader if needed
51                                 if ( ($.xmlActive <= 0) && ($.xmlDestroy) ) {
52                                         $.xmlDestroy();
53                                         $.xmlActive = 0
54                                 }
55
56                                 // Process result
57                                 if ( ret )
58                                         ret(xml);
59                         }
60                 };
61
62                 xml.send(data)
63         }
64 };
65
66 $.httpData = function(r,type) {
67         return r.getResponseHeader("content-type").indexOf("xml") > 0 || type == "xml" ?
68                 r.responseXML : r.responseText;
69 };
70
71 $.get = function( url, ret, type ) {
72         $.xml( "GET", url, null, function(r) {
73                 if ( ret ) { ret( $.httpData(r,type) ); }
74         });
75 };
76
77 $.getXML = function( url, ret ) {
78         $.get( url, ret, "xml" );
79 };
80
81 $.post = function( url, data, ret, type ) {
82         $.xml( "POST", url, $.param(data), function(r) {
83                 if ( ret ) { ret( $.httpData(r,type) ); }
84         });
85 };
86
87 $.postXML = function( url, data, ret ) {
88         $.post( url, data, ret, "xml" );
89 };
90
91 $.param = function(a) {
92         var s = [];
93         if (a && typeof a == 'object' && a.constructor == Array) {
94                 for ( var i=0; i < a.length; i++ ) {
95                         s[s.length] = a[i].name + "=" + encodeURIComponent( a[i].value );
96                 }
97         } else {
98                 for ( var j in a ) {
99                         s[s.length] = j + "=" + encodeURIComponent( a[j] );
100                 }
101         }
102         return s.join("&");
103 };
104
105 $.fn.load = function(a,o,f) {
106         // Arrrrghhhhhhhh!!
107         // I overwrote the event plugin's .load
108         // this won't happen again, I hope -John
109         if ( a && a.constructor == Function ) {
110                 return this.bind("load", a);
111         }
112
113         var t = "GET";
114         if ( o && o.constructor == Function ) {
115                 f = o;
116                 o = null;
117         }
118         if (o !== null) {
119                 o = $.param(o);
120                 t = "POST";
121         }
122         var self = this;
123         $.xml(t,a,o,function(h){
124                 h = h.responseText;
125                 self.html(h).find("script").each(function(){
126                         try {
127                                 $.eval( this.text || this.textContent || this.innerHTML );
128                         } catch(e){}
129                 });
130                 if(f){f(h);}
131         });
132         return this;
133 };
134
135 /**
136  * name:       $.fn.formValues
137  * example:    $('#frmLogin').formValues('sButton')
138  * docs:       Gets form values and creates a key=>value array of the found values.
139  *             Optionally adds the button which is clicked if you provide it.
140  *             Only does this for ENABLED elements in the order of the form.
141  */
142 $.fn.formValues = function(sButton) {
143         var a = [];
144         var elp = {INPUT:true, TEXTAREA:true, OPTION:true};
145
146         // Loop the shite
147         $('*', this).each(function() {
148                 // Skip elements not of the types in elp
149                 if (!elp[this.tagName])
150                         return;
151
152                 // Skip disabled elements
153                 if (this.disabled)
154                         return;
155
156                 // Skip non-selected nodes
157                 if ((this.parentNode.nodeName == 'SELECT') && (!this.selected))
158                         return;
159
160                 // Skip non-checked nodes
161                 if (((this.type == 'radio') || (this.type == 'checkbox')) && (!this.checked))
162                         return;
163
164                 // If we come here, everything is fine, so add the data
165                 a.push({
166                         name: this.name || this.id || this.parentNode.name || this.parentNode.id,
167                         value: this.value
168                 });
169         });
170
171         // Add submit button if needed
172         if (sButton && (sButton !== null))
173                 a.push({ name: sButton, value: 'x' });
174
175         return a;
176 };
177
178 /**
179  * name:       $.fn.update
180  * example:    $('someJQueryObject').update('sURL', 'sAction', 'aValues', 'fCallback');
181  * docs:       Calls sURL with sAction and sends the aValues
182  *                  Puts the results from that call in the jQuery object and calls fCallback
183  */
184 $.fn.update = function(sURL, sMethod, aValues, fCallback) {
185         var el = this;
186
187         // Process
188         $.xml(
189                 sMethod || "GET",
190                 sURL || "",
191                 $.param(aValues),
192                 function(sResult) {
193                         sResult = $.httpData(sResult);
194
195                         // Update the element with the new HTML
196                         el.html(sResult);
197
198                         // Evaluate the scripts AFTER this (so you can allready modify the new HTML!)
199                         el.html(sResult).find("script").each(function(){
200                                 try { $.eval( this.text || this.textContent || this.innerHTML ); } catch(e) { }
201                         });
202
203                         // And call the callback handler :)
204                         if (fCallback && (fCallback.constructor == Function))
205                                 fCallback();
206                 }
207         );
208 };
209
210 /**
211  * name:                        $.fn.serialize
212  * example:    $('someJQueryObject').serialize('sButton', 'fCallback');
213  * docs:       Calls the form's action with the correct method and the serialized values.
214  *             Optionally adds the button which is clicked if you provide it.
215  *             When there are results, the fCallback function is called.
216  */
217 $.fn.serialize = function(sButton, fCallback) {
218         var el = this.get(0);
219
220         // Process
221         $.xml(
222                 el.method || "GET",
223                 el.action || "",
224                 $.param(this.formValues(sButton)),
225                 function(sResult) {
226                         if (fCallback && (fCallback.constructor == Function))
227                                 fCallback($.httpData(sResult));
228                 }
229         );
230 };