1CGI::Ajax(3) User Contributed Perl Documentation CGI::Ajax(3)
2
3
4
6 CGI::Ajax - a perl-specific system for writing Asynchronous web appli‐
7 cations
8
10 use strict;
11 use CGI; # or any other CGI:: form handler/decoder
12 use CGI::Ajax;
13
14 my $cgi = new CGI;
15 my $pjx = new CGI::Ajax( 'exported_func' => \&perl_func );
16
17 print $pjx->build_html( $cgi, \&Show_HTML);
18
19 sub perl_func {
20 my $input = shift;
21 # do something with $input
22 my $output = $input . " was the input!";
23 return( $output );
24 }
25
26 sub Show_HTML {
27 my $html = <<EOHTML;
28 <HTML>
29 <BODY>
30 Enter something:
31 <input type="text" name="val1" id="val1"
32 onkeyup="exported_func( ['val1'], ['resultdiv'] );">
33 <br>
34 <div id="resultdiv"></div>
35 </BODY>
36 </HTML>
37 EOHTML
38 return $html;
39 }
40
41 There are several fully-functional examples in the 'scripts/' directory
42 of the distribution.
43
45 CGI::Ajax is an object-oriented module that provides a unique mechanism
46 for using perl code asynchronously from javascript- enhanced HTML
47 pages. CGI::Ajax unburdens the user from having to write extensive
48 javascript, except for associating an exported method with a document-
49 defined event (such as onClick, onKeyUp, etc). CGI::Ajax also mixes
50 well with HTML containing more complex javascript.
51
52 CGI::Ajax supports methods that return single results or multiple
53 results to the web page, and supports returning values to multiple DIV
54 elements on the HTML page.
55
56 Using CGI::Ajax, the URL for the HTTP GET/POST request is automatically
57 generated based on HTML layout and events, and the page is then dynami‐
58 cally updated with the output from the perl function. Additionally,
59 CGI::Ajax supports mapping URL's to a CGI::Ajax function name, so you
60 can separate your code processing over multiple scripts.
61
62 Other than using the Class::Accessor module to generate CGI::Ajax'
63 accessor methods, CGI::Ajax is completely self-contained - it does not
64 require you to install a larger package or a full Content Management
65 System, etc.
66
67 We have added support for other CGI handler/decoder modules, like
68 CGI::Simple or CGI::Minimal, but we can't test these since we run
69 mod_perl2 only here. CGI::Ajax checks to see if a header() method is
70 available to the CGI object, and then uses it. If method() isn't
71 available, it creates it's own minimal header.
72
73 A primary goal of CGI::Ajax is to keep the module streamlined and maxi‐
74 mally flexible. We are trying to keep the generated javascript code to
75 a minimum, but still provide users with a variety of methods for
76 deploying CGI::Ajax. And VERY little user javascript.
77
79 The CGI::Ajax module allows a Perl subroutine to be called asyn‐
80 chronously, when triggered from a javascript event on the HTML page.
81 To do this, the subroutine must be registered, usually done during:
82
83 my $pjx = new CGI::Ajax( 'JSFUNC' => \&PERLFUNC );
84
85 This maps a perl subroutine (PERLFUNC) to an automatically generated
86 Javascript function (JSFUNC). Next you setup a trigger this function
87 when an event occurs (e.g. "onClick"):
88
89 onClick="JSFUNC(['source1','source2'], ['dest1','dest2']);"
90
91 where 'source1', 'dest1', 'source2', 'dest2' are the DIV ids of HTML
92 elements in your page...
93
94 <input type=text id=source1>
95 <input type=text id=source2>
96 <div id=dest1></div>
97 <div id=dest2></div>
98
99 CGI::Ajax sends the values from source1 and source2 to your Perl sub‐
100 routine and returns the results to dest1 and dest2.
101
102 4 Usage Methods
103
104 1 Standard CGI::Ajax example
105 Start by defining a perl subroutine that you want available from
106 javascript. In this case we'll define a subrouting that determines
107 whether or not an input is odd, even, or not a number (NaN):
108
109 use strict;
110 use CGI::Ajax;
111 use CGI;
112
113 sub evenodd_func {
114 my $input = shift;
115
116 # see if input is defined
117 if ( not defined $input ) {
118 return("input not defined or NaN");
119 }
120
121 # see if value is a number (*thanks Randall!*)
122 if ( $input !~ /\A\d+\z/ ) {
123 return("input is NaN");
124 }
125
126 # got a number, so mod by 2
127 $input % 2 == 0 ? return("EVEN") : return("ODD");
128 }
129
130 Alternatively, we could have used coderefs to associate an exported
131 name...
132
133 my $evenodd_func = sub {
134 # exactly the same as in the above subroutine
135 };
136
137 Next we define a function to generate the web page - this can be
138 done many different ways, and can also be defined as an anonymous
139 sub. The only requirement is that the sub send back the html of
140 the page. You can do this via a string containing the html, or
141 from a coderef that returns the html, or from a function (as shown
142 here)...
143
144 sub Show_HTML {
145 my $html = <<EOT;
146 <HTML>
147 <HEAD><title>CGI::Ajax Example</title>
148 </HEAD>
149 <BODY>
150 Enter a number:
151 <input type="text" name="somename" id="val1" size="6"
152 OnKeyUp="evenodd( ['val1'], ['resultdiv'] );">
153 <br>
154 <hr>
155 <div id="resultdiv">
156 </div>
157 </BODY>
158 </HTML>
159 EOT
160 return $html;
161 }
162
163 The exported Perl subrouting is triggered using the "OnKeyUp" event
164 handler of the input HTML element. The subroutine takes one value
165 from the form, the input element 'val1', and returns the the result
166 to an HTML div element with an id of 'resultdiv'. Sending in the
167 input id in an array format is required to support multiple inputs,
168 and similarly, to output multiple the results, you can use an array
169 for the output divs, but this isn't mandatory - as will be
170 explained in the Advanced usage.
171
172 Now create a CGI object and a CGI::Ajax object, associating a ref‐
173 erence to our subroutine with the name we want available to
174 javascript.
175
176 my $cgi = new CGI();
177 my $pjx = new CGI::Ajax( 'evenodd' => \&evenodd_func );
178
179 And if we used a coderef, it would look like this...
180
181 my $pjx = new CGI::Ajax( 'evenodd' => $evenodd_func );
182
183 Now we're ready to print the output page; we send in the cgi object
184 and the HTML-generating function.
185
186 print $pjx->build_html($cgi,\&Show_HTML);
187
188 CGI::Ajax has support for passing in extra HTML header information
189 to the CGI object. This can be accomplished by adding a third
190 argument to the build_html() call. The argument needs to be a
191 hashref containing Key=>value pairs that CGI objects understand:
192
193 print $pjx->build_html($cgi,\&Show_HTML,
194 {-charset=>'UTF-8, -expires=>'-1d'});
195
196 See CGI for more header() method options. (CGI.pm, not the Perl6
197 CGI)
198
199 That's it for the CGI::Ajax standard method. Let's look at some‐
200 thing more advanced.
201
202 2 Advanced CGI::Ajax example
203 Let's say we wanted to have a perl subroutine process multiple val‐
204 ues from the HTML page, and similarly return multiple values back
205 to distinct divs on the page. This is easy to do, and requires no
206 changes to the perl code - you just create it as you would any perl
207 subroutine that works with multiple input values and returns multi‐
208 ple values. The significant change happens in the event handler
209 javascript in the HTML...
210
211 onClick="exported_func(['input1','input2'],['result1','result2']);"
212
213 Here we associate our javascript function ("exported_func") with
214 two HTML element ids ('input1','input2'), and also send in two HTML
215 element ids to place the results in ('result1','result2').
216
217 3 Sending Perl Subroutine Output to a Javascript function
218 Occassionally, you might want to have a custom javascript function
219 process the returned information from your Perl subroutine. This
220 is possible, and the only requierment is that you change your event
221 handler code...
222
223 onClick="exported_func(['input1'],[js_process_func]);"
224
225 In this scenario, "js_process_func" is a javascript function you
226 write to take the returned value from your Perl subroutine and
227 process the results. Note that a javascript function is not quoted
228 -- if it were, then CGI::Ajax would look for a HTML element with
229 that id. Beware that with this usage, you are responsible for dis‐
230 tributing the results to the appropriate place on the HTML page.
231 If the exported Perl subroutine returns, e.g. 2 values, then
232 "js_process_func" would need to process the input by working
233 through an array, or using the javascript Function "arguments"
234 object.
235
236 function js_process_func() {
237 var input1 = arguments[0]
238 var input2 = arguments[1];
239 // do something and return results, or set HTML divs using
240 // innerHTML
241 document.getElementById('outputdiv').innerHTML = input1;
242 }
243
244 4 URL/Outside Script CGI::Ajax example
245 There are times when you may want a different script to return con‐
246 tent to your page. This could be because you have an existing
247 script already written to perform a particular task, or you want to
248 distribute a part of your application to another script. This can
249 be accomplished in CGI::Ajax by using a URL in place of a locally-
250 defined Perl subroutine. In this usage, you alter you creation of
251 the CGI::Ajax object to link an exported javascript function name
252 to a local URL instead of a coderef or a subroutine.
253
254 my $url = 'scripts/other_script.pl';
255 my $pjx = new CGI::Ajax( 'external' => $url );
256
257 This will work as before in terms of how it is called from you
258 event handler:
259
260 onClick="external(['input1','input2'],['resultdiv']);"
261
262 The other_script.pl will get the values via a CGI object and
263 accessing the 'args' key. The values of the 'args' key will be an
264 array of everything that was sent into the script.
265
266 my @input = $cgi->params('args');
267 $input[0]; # contains first argument
268 $input[1]; # contains second argument, etc...
269
270 This is good, but what if you need to send in arguments to the
271 other script which are directly from the calling Perl script, i.e.
272 you want a calling Perl script's variable to be sent, not the value
273 from an HTML element on the page? This is possible using the fol‐
274 lowing syntax:
275
276 onClick="exported_func(['args__$input1','args__$input2'],
277 ['resultdiv']);"
278
279 Similary, if the external script required a constant as input (e.g.
280 "script.pl?args=42", you would use this syntax:
281
282 onClick="exported_func(['args__42'],['resultdiv']);"
283
284 In both of the above examples, the result from the external script
285 would get placed into the resultdiv element on our (the calling
286 script's) page.
287
288 If you are sending more than one argument from an external perl
289 script back to a javascript function, you will need to split the
290 string (AJAX applications communicate in strings only) on some‐
291 thing. Internally, we use '__pjx__', and this string is checked
292 for. If found, CGI::Ajax will automatically split it. However, if
293 you don't want to use '__pjx__', you can do it yourself:
294
295 For example, from your Perl script, you would...
296
297 return("A⎪B"); # join with "⎪"
298
299 and then in the javascript function you would have something
300 like...
301
302 process_func() {
303 var arr = arguments[0].split("⎪");
304 // arr[0] eq 'A'
305 // arr[1] eq 'B'
306 }
307
308 In order to rename parameters, in case the outside script needs
309 specifically-named parameters and not CGI::Ajax' 'args' default
310 parameter name, change your event handler associated with an HTML
311 event like this
312
313 onClick="exported_func(['myname__$input1','myparam__$input2'],
314 ['resultdiv']);"
315
316 The URL generated would look like this...
317
318 "script.pl?myname=input1&myparam=input2"
319
320 You would then retrieve the input in the outside script with
321 this...
322
323 my $p1 = $cgi->params('myname');
324 my $p1 = $cgi->params('myparam');
325
326 Finally, what if we need to get a value from our HTML page and we
327 want to send that value to an outside script but the outside script
328 requires a named parameter different from 'args'? You can accom‐
329 plish this with CGI::Ajax using the getVal() javascript method
330 (which returns an array, thus the "getVal()[0]" notation):
331
332 onClick="exported_func(['myparam__' + getVal('div_id')[0]],
333 ['resultdiv']);"
334
335 This will get the value of our HTML element with and id of div_id,
336 and submit it to the url attached to myparam__. So if our exported
337 handler referred to a URI called script/scr.pl, and the element on
338 our HTML page called div_id contained the number '42', then the URL
339 would look like this "script/scr.pl?myparam=42". The result from
340 this outside URL would get placed back into our HTML page in the
341 element resultdiv. See the example script that comes with the dis‐
342 tribution called pjx_url.pl and its associated outside script con‐
343 vert_degrees.pl for a working example.
344
345 N.B. These examples show the use of outside scripts which are other
346 perl scripts - but you are not limited to Perl! The outside script
347 could just as easily have been PHP or any other CGI script, as long
348 as the return from the other script is just the result, and not
349 addition HTML code (like FORM elements, etc).
350
351 GET versus POST
352
353 Note that all the examples so far have used the following syntax:
354
355 onClick="exported_func(['input1'],['result1']);"
356
357 There is an optional third argument to a CGI::Ajax exported function
358 that allows change the submit method. The above event could also have
359 been coded like this...
360
361 onClick="exported_func(['input1'],['result1'], 'GET');"
362
363 By default, CGI::Ajax sends a 'GET' request. If you need it, for exam‐
364 ple your URL is getting way too long, you can easily switch to a 'POST'
365 request with this syntax...
366
367 onClick="exported_func(['input1'],['result1'], 'POST');"
368
369 ('POST' and 'post' are supported)
370
371 Page Caching
372
373 We have implemented a method to prevent page cacheing from undermining
374 the AJAX methods in a page. If you send in an input argument to a
375 CGI::Ajax-exported function called 'NO_CACHE', the a special parameter
376 will get attached to the end or your url with a random number in it.
377 This will prevent a browser from caching your request.
378
379 onClick="exported_func(['input1','NO_CACHE'],['result1']);"
380
381 The extra param is called pjxrand, and won't interfere with the order
382 of processing for the rest of your parameters.
383
385 build_html()
386 Purpose: Associates a cgi obj ($cgi) with pjx object, inserts
387 javascript into <HEAD></HEAD> element and constructs
388 the page, or part of the page. AJAX applications
389 are designed to update only the section of the
390 page that needs it - the whole page doesn't have
391 to be redrawn. L<CGI::Ajax> applications use the
392 build_html() method to take care of this: if the CGI
393 parameter C<fname> exists, then the return from the
394 L<CGI::Ajax>-exported function is sent to the page.
395 Otherwise, the entire page is sent, since without
396 an C<fname> param, this has to be the first time
397 the page is being built.
398
399 Arguments: The CGI object, and either a coderef, or a string
400 containing html. Optionally, you can send in a third
401 parameter containing information that will get passed
402 directly to the CGI object header() call.
403 Returns: html or updated html (including the header)
404 Called By: originating cgi script
405
406 show_javascript()
407 Purpose: builds the text of all the javascript that needs to be
408 inserted into the calling scripts html <head> section
409 Arguments:
410 Returns: javascript text
411 Called By: originating web script
412 Note: This method is also overridden so when you just print
413 a CGI::Ajax object it will output all the javascript needed
414 for the web page.
415
416 register()
417 Purpose: adds a function name and a code ref to the global coderef
418 hash, after the original object was created
419 Arguments: function name, code reference
420 Returns: none
421 Called By: originating web script
422
423 JSDEBUG()
424 Purpose: Show the AJAX URL that is being generated, and stop
425 compression of the generated javascript, both of which can aid
426 during debugging. If set to 1, then the core js will get
427 compressed, but the user-defined functions will not be
428 compressed. If set to 2 (or anything greater than 1 or 0),
429 then none of the javascript will get compressed.
430
431 Arguments: JSDEBUG(0); # turn javascript debugging off
432 JSDEBUG(1); # turn javascript debugging on, some javascript compression
433 JSDEBUG(2); # turn javascript debugging on, no javascript compresstion
434 Returns: prints a link to the url that is being generated automatically by
435 the Ajax object. this is VERY useful for seeing what
436 CGI::Ajax is doing. Following the link, will show a page
437 with the output that the page is generating.
438
439 Called By: $pjx->JSDEBUG(1) # where $pjx is a CGI::Ajax object;
440
441 DEBUG()
442 Purpose: Show debugging information in web server logs
443 Arguments: DEBUG(0); # turn debugging off (default)
444 DEBUG(1); # turn debugging on
445 Returns: prints debugging information to the web server logs using
446 STDERR
447 Called By: $pjx->DEBUG(1) # where $pjx is a CGI::Ajax object;
448
450 Follow any bugs at our homepage....
451
452 http://www.perljax.us
453
455 Check out the news/discussion/bugs lists at our homepage:
456
457 http://www.perljax.us
458
460 Brian C. Thomas Brent Pedersen
461 CPAN ID: BCT
462 bct.x42@gmail.com bpederse@gmail.com
463
464 significant contribution by:
465 Peter Gordon <peter@pg-consultants.com> # CGI::Application + scripts
466 Kyraha <kyraha@gmail.com> # new getVal() to handle check boxes
467 and name= for multiple forms
468
470 This module was initiated using the name "Perljax", but then registered
471 with CPAN under the WWW group "CGI::", and so became "CGI::Perljax".
472 Upon further deliberation, we decided to change it's name to CGI::Ajax.
473
475 This program is free software; you can redistribute it and/or modify it
476 under the same terms as Perl itself.
477
478 The full text of the license can be found in the LICENSE file included
479 with this module.
480
482 Data::Javascript CGI Class::Accessor
483
484
485
486perl v5.8.8 2007-01-31 CGI::Ajax(3)