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