summaryrefslogtreecommitdiff
path: root/framework/Web/Javascripts/prado/ajax3.js
blob: 1cffbd7300cb11d31da1a0d4d08faccaff48c923 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/**
 * Override Prototype's response implementation.
 */
Object.extend(Ajax.Request.prototype,
{
	/**
	 * Customize the response, dispatch onXXX response code events, and
	 * tries to execute response actions (javascript statements).
	 */
	respondToReadyState : function(readyState) 
	{
	    var event = Ajax.Request.Events[readyState];
	    var transport = this.transport, json = this.getHeaderData(Prado.CallbackRequest.DATA_HEADER);
		
	    if (event == 'Complete') 
	    {
			Ajax.Responders.dispatch('on' + transport.status, this, transport, json);
			Prado.CallbackRequest.dispatchActions(this.getHeaderData(Prado.CallbackRequest.ACTION_HEADER));
	      
	      try {
	        (this.options['on' + this.transport.status]
	         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
	         || Prototype.emptyFunction)(transport, json);
	  	      } catch (e) {
	        this.dispatchException(e);
	      }
	      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
	        this.evalResponse();
	    }
	    
	    try {
	      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
	      Ajax.Responders.dispatch('on' + event, this, transport, json);
	    } catch (e) {
	      this.dispatchException(e);
	    }
	    
	    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
	    if (event == 'Complete')
	      this.transport.onreadystatechange = Prototype.emptyFunction;
	},
	
	/**
	 * Gets header data assuming JSON encoding.
	 * @param string header name
	 * @return object header data as javascript structures.
	 */
	getHeaderData : function(name)
	{
		try 
		{
			var json = this.header(name);
			return eval('(' + json + ')');
		} 
		catch (e) 
		{
			if(typeof(json) == "string")
			{
				Logger.info("using json")
				return Prado.CallbackRequest.decode(json);
			}
		}
	}
});

/**
 * Prado Callback client-side request handler.
 */
Prado.CallbackRequest = Class.create();

/**
 * Static definitions.
 */
Object.extend(Prado.CallbackRequest,
{
	/**
	 * Callback request target POST field name.
	 */
	FIELD_CALLBACK_TARGET : 'PRADO_CALLBACK_TARGET',
	/**
	 * Callback request parameter POST field name.
	 */
	FIELD_CALLBACK_PARAMETER : 'PRADO_CALLBACK_PARAMETER',
	/**
	 * List of form fields that will be collected during callback.
	 */
	PostDataLoaders : ['PRADO_PAGESTATE'],
	/**
	 * Response data header name.
	 */
	DATA_HEADER : 'X-PRADO-DATA',
	/**
	 * Response javascript execution statement header name.
	 */
	ACTION_HEADER : 'X-PRADO-ACTIONS',
	/**
	 * Response errors/exceptions header name.
	 */
	ERROR_HEADER : 'X-PRADO-ERROR',
	
	/**
	 * Dispatch callback response actions.
	 */
	dispatchActions : function(actions)
	{
		actions.each(this.__run);
	},
	
	/**
	 * Prase and evaluate a Callback clien-side action
	 */
	__run : function(command)
	{
		for(var method in command)
		{
			if(command[method][0])
			{
				var id = command[method][0];
				if($(id) || id.indexOf("[]") > -1)
					method.toFunction().apply(this,command[method]);
				else if(typeof(Logger) != "undefined")
				{
					Logger.error("Error in executing callback response:", 
					"Unable to find HTML element with ID '"+id+"' before executing "+method+"().");		
				}
			}
		}
	},
	
	/**
	 * Respond to Prado Callback request exceptions.
	 */
	Exception :
	{
		/**
		 * Server returns 505 exception. Just log it.
		 */
		"on505" : function(request, transport, data)
		{	
			var e = request.getHeaderData(Prado.CallbackRequest.ERROR_HEADER);
			Logger.error("Callback Server Error "+e.code, this.formatException(e));
		},
		
		/**
		 * Callback OnComplete event,logs reponse and data to console.
		 */
		'on200' : function(request, transport, data)
		{
			if(transport.status < 500)
			{
				var msg = 'HTTP '+transport.status+" with response : \n";
				msg += transport.responseText + "\n";
				msg += "Data : \n"+inspect(data)+"\n";
				msg += "Actions : \n";
				request.getHeaderData(Prado.CallbackRequest.ACTION_HEADER).each(function(action)
				{
					msg += inspect(action)+"\n";
				})
				
				Logger.warn(msg);
			}
		},
	
		/**
		 * Uncaught exceptions during callback response.
		 */
		onException : function(e)
		{
			Logger.error('Uncaught Callback Client Exception:', e);
		},
	
		/**
		 * Formats the exception message for display in console.
		 */
		formatException : function(e)
		{
			var msg = e.type + " with message \""+e.message+"\"";
			msg += " in "+e.file+"("+e.line+")\n";
			msg += "Stack trace:\n";
			var trace = e.trace;
			for(var i = 0; i<trace.length; i++)
			{
				msg += "  #"+i+" "+trace[i].file;
				msg += "("+trace[i].line+"): ";
				msg += trace[i]["class"]+"->"+trace[i]["function"]+"()"+"\n";
			}
			msg += e.version+" "+e.time+"\n";
			return msg;
		}
	},
	
	/**
	 * @return string JSON encoded data.
	 */
	encode : function(data)
	{
		return Prado.JSON.stringify(data);
	},
	
	/**
	 * @return mixed javascript data decoded from string using JSON decoding.
	 */
	decode : function(data)
	{
		return Prado.JSON.parse(data);
	}
})

//Add HTTP exception respones when logger is enabled.
Event.OnLoad(function()
{ 
	if(typeof Logger != "undefined") 
		Ajax.Responders.register(Prado.CallbackRequest.Exception);
});

/**
 * Create and prepare a new callback request.
 */
Prado.CallbackRequest.prototype = 
{
	/**
	 * Callback URL, same url as the current page.
	 */
	url : window.location.href,
	
	/**
	 * Callback options, including onXXX events.
	 */
	options : {},
	
	/**
	 * Callback target ID. E.g. $control->getUniqueID();
	 */
	id : null,
	
	/**
	 * Current callback request.
	 */
	request : null,
	
	/**
	 * Prepare and inititate a callback request.
	 */
	initialize : function(id, options)
	{
		this.options = options || {};	
		this.id = id;
		
		var request = 
		{
			postBody : this._getPostData(),
			parameters : ''
		}
		Object.extend(this.options || {},request);
		if(this.options.CausesValidation != false && typeof(Prado.Validation) != "undefined")
		{
			var form =  this.options.Form || Prado.Validation.getForm();
			if(Prado.Validation.validate(form,this.options.ValidationGroup,this) == false)
				return;
		}
		this.request = new Ajax.Request(this.url, this.options);
	},

	/**
	 * Collects the form inputs, encode the parameters, and sets the callback 
	 * target id. The resulting string is the request content body.
	 * @return string request body content containing post data.
	 */
	_getPostData : function()
	{
		var data = {};
		
		Prado.CallbackRequest.PostDataLoaders.each(function(name)
		{
			$A(document.getElementsByName(name)).each(function(element)
			{
				var value = $F(element);
				if(typeof(value) != "undefined")
					data[name] = value;
			})
		})
		if(typeof(this.options.params) != "undefined")
			data[Prado.CallbackRequest.FIELD_CALLBACK_PARAMETER] = Prado.CallbackRequest.encode(this.options.params);
		data[Prado.CallbackRequest.FIELD_CALLBACK_TARGET] = this.id;
		return $H(data).toQueryString();
	}
}

/**
 * Create a new callback request using default settings.
 * @param string callback handler unique ID.
 * @param mixed parameter to pass to callback handler on the server side.
 * @param function client side onSuccess event handler.
 * @param object additional request options.
 * @return boolean always false.
 */
Prado.Callback = function(UniqueID, parameter, onSuccess, options)
{
	var callback =  
	{
		'params' : parameter || '',
		'onSuccess' : onSuccess || Prototype.emptyFunction, 
		'CausesValidation' : true
	};

	Object.extend(callback, options || {});
	
	new Prado.CallbackRequest(UniqueID, callback);
	return false;
}