{
    "content": [
        {
            "type": "text",
            "text": "# CGI::Ajax (perldoc)\n\n## NAME\n\nCGI::Ajax - a perl-specific system for writing Asynchronous web applications\n\n## SYNOPSIS\n\nuse strict;\nuse CGI;      # or any other CGI:: form handler/decoder\nuse CGI::Ajax;\nmy $cgi = new CGI;\nmy $pjx = new CGI::Ajax( 'exportedfunc' => \\&perlfunc );\nprint $pjx->buildhtml( $cgi, \\&ShowHTML);\nsub perlfunc {\nmy $input = shift;\n# do something with $input\nmy $output = $input . \" was the input!\";\nreturn( $output );\n}\nsub ShowHTML {\nmy $html = <<EOHTML;\n<HTML>\n<BODY>\nEnter something:\n<input type=\"text\" name=\"val1\" id=\"val1\"\nonkeyup=\"exportedfunc( ['val1'], ['resultdiv'] );\">\n<br>\n<div id=\"resultdiv\"></div>\n</BODY>\n</HTML>\nEOHTML\nreturn $html;\n}\nWhen you use CGI::Ajax within Applications that send their own header information, you can skip\nthe header:\nmy $pjx = new CGI::Ajax(\n'exportedfunc' => \\&perlfunc,\n'skipheader'   => 1,\n);\n$pjx->skipheader(1);\nprint $pjx->buildhtml( $cgi, \\&ShowHTML);\n*There are several fully-functional examples in the 'scripts/' directory of the distribution.*\n\n## DESCRIPTION\n\nCGI::Ajax is an object-oriented module that provides a unique mechanism for using perl code\nasynchronously from javascript- enhanced HTML pages. CGI::Ajax unburdens the user from having to\nwrite extensive javascript, except for associating an exported method with a document-defined\nevent (such as onClick, onKeyUp, etc). CGI::Ajax also mixes well with HTML containing more\ncomplex javascript.\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS**\n- **DESCRIPTION**\n- **EXAMPLES** (1 subsections)\n- **METHODS** (4 subsections)\n- **BUGS**\n- **SUPPORT**\n- **AUTHORS**\n- **A NOTE ABOUT THE MODULE NAME**\n- **COPYRIGHT**\n- **SEE ALSO**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "CGI::Ajax",
        "section": "",
        "mode": "perldoc",
        "summary": "CGI::Ajax - a perl-specific system for writing Asynchronous web applications",
        "synopsis": "use strict;\nuse CGI;      # or any other CGI:: form handler/decoder\nuse CGI::Ajax;\nmy $cgi = new CGI;\nmy $pjx = new CGI::Ajax( 'exportedfunc' => \\&perlfunc );\nprint $pjx->buildhtml( $cgi, \\&ShowHTML);\nsub perlfunc {\nmy $input = shift;\n# do something with $input\nmy $output = $input . \" was the input!\";\nreturn( $output );\n}\nsub ShowHTML {\nmy $html = <<EOHTML;\n<HTML>\n<BODY>\nEnter something:\n<input type=\"text\" name=\"val1\" id=\"val1\"\nonkeyup=\"exportedfunc( ['val1'], ['resultdiv'] );\">\n<br>\n<div id=\"resultdiv\"></div>\n</BODY>\n</HTML>\nEOHTML\nreturn $html;\n}\nWhen you use CGI::Ajax within Applications that send their own header information, you can skip\nthe header:\nmy $pjx = new CGI::Ajax(\n'exportedfunc' => \\&perlfunc,\n'skipheader'   => 1,\n);\n$pjx->skipheader(1);\nprint $pjx->buildhtml( $cgi, \\&ShowHTML);\n*There are several fully-functional examples in the 'scripts/' directory of the distribution.*",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [
            "The CGI::Ajax module allows a Perl subroutine to be called asynchronously, when triggered from a",
            "javascript event on the HTML page. To do this, the subroutine must be *registered*, usually done",
            "during:",
            "my $pjx = new CGI::Ajax( 'JSFUNC' => \\&PERLFUNC );",
            "This maps a perl subroutine (PERLFUNC) to an automatically generated Javascript function",
            "(JSFUNC). Next you setup a trigger this function when an event occurs (e.g. \"onClick\"):",
            "onClick=\"JSFUNC(['source1','source2'], ['dest1','dest2']);\"",
            "where 'source1', 'dest1', 'source2', 'dest2' are the DIV ids of HTML elements in your page...",
            "<input type=text id=source1>",
            "<input type=text id=source2>",
            "<div id=dest1></div>",
            "<div id=dest2></div>",
            "CGI::Ajax sends the values from source1 and source2 to your Perl subroutine and returns the",
            "results to dest1 and dest2.",
            "4 Usage Methods",
            "1 Standard CGI::Ajax example",
            "Start by defining a perl subroutine that you want available from javascript. In this case",
            "we'll define a subrouting that determines whether or not an input is odd, even, or not a",
            "number (NaN):",
            "use strict;",
            "use CGI::Ajax;",
            "use CGI;",
            "sub evenoddfunc {",
            "my $input = shift;",
            "# see if input is defined",
            "if ( not defined $input ) {",
            "return(\"input not defined or NaN\");",
            "# see if value is a number (*thanks Randall!*)",
            "if ( $input !~ /\\A\\d+\\z/ ) {",
            "return(\"input is NaN\");",
            "# got a number, so mod by 2",
            "$input % 2 == 0 ? return(\"EVEN\") : return(\"ODD\");",
            "Alternatively, we could have used coderefs to associate an exported name...",
            "my $evenoddfunc = sub {",
            "# exactly the same as in the above subroutine",
            "};",
            "Next we define a function to generate the web page - this can be done many different ways,",
            "and can also be defined as an anonymous sub. The only requirement is that the sub send back",
            "the html of the page. You can do this via a string containing the html, or from a coderef",
            "that returns the html, or from a function (as shown here)...",
            "sub ShowHTML {",
            "my $html = <<EOT;",
            "<HTML>",
            "<HEAD><title>CGI::Ajax Example</title>",
            "</HEAD>",
            "<BODY>",
            "Enter a number:&nbsp;",
            "<input type=\"text\" name=\"somename\" id=\"val1\" size=\"6\"",
            "OnKeyUp=\"evenodd( ['val1'], ['resultdiv'] );\">",
            "<br>",
            "<hr>",
            "<div id=\"resultdiv\">",
            "</div>",
            "</BODY>",
            "</HTML>",
            "EOT",
            "return $html;",
            "The exported Perl subrouting is triggered using the \"OnKeyUp\" event handler of the input",
            "HTML element. The subroutine takes one value from the form, the input element 'val1', and",
            "returns the the result to an HTML div element with an id of 'resultdiv'. Sending in the",
            "input id in an array format is required to support multiple inputs, and similarly, to output",
            "multiple the results, you can use an array for the output divs, but this isn't mandatory -",
            "as will be explained in the Advanced usage.",
            "Now create a CGI object and a CGI::Ajax object, associating a reference to our subroutine",
            "with the name we want available to javascript.",
            "my $cgi = new CGI();",
            "my $pjx = new CGI::Ajax( 'evenodd' => \\&evenoddfunc );",
            "And if we used a coderef, it would look like this...",
            "my $pjx = new CGI::Ajax( 'evenodd' => $evenoddfunc );",
            "Now we're ready to print the output page; we send in the cgi object and the HTML-generating",
            "function.",
            "print $pjx->buildhtml($cgi,\\&ShowHTML);",
            "CGI::Ajax has support for passing in extra HTML header information to the CGI object. This",
            "can be accomplished by adding a third argument to the buildhtml() call. The argument needs",
            "to be a hashref containing Key=>value pairs that CGI objects understand:",
            "print $pjx->buildhtml($cgi,\\&ShowHTML,",
            "{-charset=>'UTF-8, -expires=>'-1d'});",
            "See CGI for more header() method options. (CGI.pm, not the Perl6 CGI)",
            "That's it for the CGI::Ajax standard method. Let's look at something more advanced.",
            "2 Advanced CGI::Ajax example",
            "Let's say we wanted to have a perl subroutine process multiple values from the HTML page,",
            "and similarly return multiple values back to distinct divs on the page. This is easy to do,",
            "and requires no changes to the perl code - you just create it as you would any perl",
            "subroutine that works with multiple input values and returns multiple values. The",
            "significant change happens in the event handler javascript in the HTML...",
            "onClick=\"exportedfunc(['input1','input2'],['result1','result2']);\"",
            "Here we associate our javascript function (\"exportedfunc\") with two HTML element ids",
            "('input1','input2'), and also send in two HTML element ids to place the results in",
            "('result1','result2').",
            "3 Sending Perl Subroutine Output to a Javascript function",
            "Occassionally, you might want to have a custom javascript function process the returned",
            "information from your Perl subroutine. This is possible, and the only requierment is that",
            "you change your event handler code...",
            "onClick=\"exportedfunc(['input1'],[jsprocessfunc]);\"",
            "In this scenario, \"jsprocessfunc\" is a javascript function you write to take the returned",
            "value from your Perl subroutine and process the results. *Note that a javascript function is",
            "not quoted -- if it were, then CGI::Ajax would look for a HTML element with that id.* Beware",
            "that with this usage, you are responsible for distributing the results to the appropriate",
            "place on the HTML page. If the exported Perl subroutine returns, e.g. 2 values, then",
            "\"jsprocessfunc\" would need to process the input by working through an array, or using the",
            "javascript Function \"arguments\" object.",
            "function jsprocessfunc() {",
            "var input1 = arguments[0]",
            "var input2 = arguments[1];",
            "// do something and return results, or set HTML divs using",
            "// innerHTML",
            "document.getElementById('outputdiv').innerHTML = input1;",
            "4 URL/Outside Script CGI::Ajax example",
            "There are times when you may want a different script to return content to your page. This",
            "could be because you have an existing script already written to perform a particular task,",
            "or you want to distribute a part of your application to another script. This can be",
            "accomplished in CGI::Ajax by using a URL in place of a locally-defined Perl subroutine. In",
            "this usage, you alter you creation of the CGI::Ajax object to link an exported javascript",
            "function name to a local URL instead of a coderef or a subroutine.",
            "my $url = 'scripts/otherscript.pl';",
            "my $pjx = new CGI::Ajax( 'external' => $url );",
            "This will work as before in terms of how it is called from you event handler:",
            "onClick=\"external(['input1','input2'],['resultdiv']);\"",
            "The otherscript.pl will get the values via a CGI object and accessing the 'args' key. The",
            "values of the 'args' key will be an array of everything that was sent into the script.",
            "my @input = $cgi->params('args');",
            "$input[0]; # contains first argument",
            "$input[1]; # contains second argument, etc...",
            "This is good, but what if you need to send in arguments to the other script which are",
            "directly from the calling Perl script, i.e. you want a calling Perl script's variable to be",
            "sent, not the value from an HTML element on the page? This is possible using the following",
            "syntax:",
            "onClick=\"exportedfunc(['args$input1','args$input2'],",
            "['resultdiv']);\"",
            "Similary, if the external script required a constant as input (e.g. \"script.pl?args=42\", you",
            "would use this syntax:",
            "onClick=\"exportedfunc(['args42'],['resultdiv']);\"",
            "In both of the above examples, the result from the external script would get placed into the",
            "*resultdiv* element on our (the calling script's) page.",
            "If you are sending more than one argument from an external perl script back to a javascript",
            "function, you will need to split the string (AJAX applications communicate in strings only)",
            "on something. Internally, we use 'pjx', and this string is checked for. If found,",
            "CGI::Ajax will automatically split it. However, if you don't want to use 'pjx', you can",
            "do it yourself:",
            "For example, from your Perl script, you would...",
            "return(\"A|B\"); # join with \"|\"",
            "and then in the javascript function you would have something like...",
            "processfunc() {",
            "var arr = arguments[0].split(\"|\");",
            "// arr[0] eq 'A'",
            "// arr[1] eq 'B'",
            "In order to rename parameters, in case the outside script needs specifically-named",
            "parameters and not CGI::Ajax' *'args'* default parameter name, change your event handler",
            "associated with an HTML event like this",
            "onClick=\"exportedfunc(['myname$input1','myparam$input2'],",
            "['resultdiv']);\"",
            "The URL generated would look like this...",
            "\"script.pl?myname=input1&myparam=input2\"",
            "You would then retrieve the input in the outside script with this...",
            "my $p1 = $cgi->params('myname');",
            "my $p1 = $cgi->params('myparam');",
            "Finally, what if we need to get a value from our HTML page and we want to send that value to",
            "an outside script but the outside script requires a named parameter different from *'args'*?",
            "You can accomplish this with CGI::Ajax using the getVal() javascript method (which returns",
            "an array, thus the \"getVal()[0]\" notation):",
            "onClick=\"exportedfunc(['myparam' + getVal('divid')[0]],",
            "['resultdiv']);\"",
            "This will get the value of our HTML element with and *id* of *divid*, and submit it to the",
            "url attached to *myparam*. So if our exported handler referred to a URI called",
            "*script/scr.pl*, and the element on our HTML page called *divid* contained the number '42',",
            "then the URL would look like this \"script/scr.pl?myparam=42\". The result from this outside",
            "URL would get placed back into our HTML page in the element *resultdiv*. See the example",
            "script that comes with the distribution called *pjxurl.pl* and its associated outside",
            "script *convertdegrees.pl* for a working example.",
            "N.B. These examples show the use of outside scripts which are other perl scripts - *but you",
            "are not limited to Perl*! The outside script could just as easily have been PHP or any other",
            "CGI script, as long as the return from the other script is just the result, and not addition",
            "HTML code (like FORM elements, etc).",
            "GET versus POST",
            "Note that all the examples so far have used the following syntax:",
            "onClick=\"exportedfunc(['input1'],['result1']);\"",
            "There is an optional third argument to a CGI::Ajax exported function that allows change the",
            "submit method. The above event could also have been coded like this...",
            "onClick=\"exportedfunc(['input1'],['result1'], 'GET');\"",
            "By default, CGI::Ajax sends a *'GET'* request. If you need it, for example your URL is getting",
            "way too long, you can easily switch to a *'POST'* request with this syntax...",
            "onClick=\"exportedfunc(['input1'],['result1'], 'POST');\"",
            "*('POST' and 'post' are supported)*",
            "We have implemented a method to prevent page cacheing from undermining the AJAX methods in a",
            "page. If you send in an input argument to a CGI::Ajax-exported function called 'NOCACHE', the a",
            "special parameter will get attached to the end or your url with a random number in it. This will",
            "prevent a browser from caching your request.",
            "onClick=\"exportedfunc(['input1','NOCACHE'],['result1']);\"",
            "The extra param is called pjxrand, and won't interfere with the order of processing for the rest",
            "of your parameters.",
            "Also see the CACHE() method of changing the default cache behavior."
        ],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 43,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 27,
                "subsections": []
            },
            {
                "name": "EXAMPLES",
                "lines": 258,
                "subsections": [
                    {
                        "name": "Page Caching",
                        "lines": 12
                    }
                ]
            },
            {
                "name": "METHODS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "build_html",
                        "lines": 20
                    },
                    {
                        "name": "show_javascript",
                        "lines": 9
                    },
                    {
                        "name": "register",
                        "lines": 6
                    },
                    {
                        "name": "fname",
                        "lines": 44
                    }
                ]
            },
            {
                "name": "BUGS",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "SUPPORT",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 16,
                "subsections": []
            },
            {
                "name": "A NOTE ABOUT THE MODULE NAME",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "COPYRIGHT",
                "lines": 5,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 2,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "CGI::Ajax - a perl-specific system for writing Asynchronous web applications\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use strict;\nuse CGI;      # or any other CGI:: form handler/decoder\nuse CGI::Ajax;\n\nmy $cgi = new CGI;\nmy $pjx = new CGI::Ajax( 'exportedfunc' => \\&perlfunc );\nprint $pjx->buildhtml( $cgi, \\&ShowHTML);\n\nsub perlfunc {\nmy $input = shift;\n# do something with $input\nmy $output = $input . \" was the input!\";\nreturn( $output );\n}\n\nsub ShowHTML {\nmy $html = <<EOHTML;\n<HTML>\n<BODY>\nEnter something:\n<input type=\"text\" name=\"val1\" id=\"val1\"\nonkeyup=\"exportedfunc( ['val1'], ['resultdiv'] );\">\n<br>\n<div id=\"resultdiv\"></div>\n</BODY>\n</HTML>\nEOHTML\nreturn $html;\n}\n\nWhen you use CGI::Ajax within Applications that send their own header information, you can skip\nthe header:\n\nmy $pjx = new CGI::Ajax(\n'exportedfunc' => \\&perlfunc,\n'skipheader'   => 1,\n);\n$pjx->skipheader(1);\n\nprint $pjx->buildhtml( $cgi, \\&ShowHTML);\n\n*There are several fully-functional examples in the 'scripts/' directory of the distribution.*\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "CGI::Ajax is an object-oriented module that provides a unique mechanism for using perl code\nasynchronously from javascript- enhanced HTML pages. CGI::Ajax unburdens the user from having to\nwrite extensive javascript, except for associating an exported method with a document-defined\nevent (such as onClick, onKeyUp, etc). CGI::Ajax also mixes well with HTML containing more\ncomplex javascript.\n\nCGI::Ajax supports methods that return single results or multiple results to the web page, and\nsupports returning values to multiple DIV elements on the HTML page.\n\nUsing CGI::Ajax, the URL for the HTTP GET/POST request is automatically generated based on HTML\nlayout and events, and the page is then dynamically updated with the output from the perl\nfunction. Additionally, CGI::Ajax supports mapping URL's to a CGI::Ajax function name, so you\ncan separate your code processing over multiple scripts.\n\nOther than using the Class::Accessor module to generate CGI::Ajax' accessor methods, CGI::Ajax\nis completely self-contained - it does not require you to install a larger package or a full\nContent Management System, etc.\n\nWe have added *support* for other CGI handler/decoder modules, like CGI::Simple or CGI::Minimal,\nbut we can't test these since we run modperl2 only here. CGI::Ajax checks to see if a header()\nmethod is available to the CGI object, and then uses it. If method() isn't available, it creates\nit's own minimal header.\n\nA primary goal of CGI::Ajax is to keep the module streamlined and maximally flexible. We are\ntrying to keep the generated javascript code to a minimum, but still provide users with a\nvariety of methods for deploying CGI::Ajax. And VERY little user javascript.\n",
                "subsections": []
            },
            "EXAMPLES": {
                "content": "The CGI::Ajax module allows a Perl subroutine to be called asynchronously, when triggered from a\njavascript event on the HTML page. To do this, the subroutine must be *registered*, usually done\nduring:\n\nmy $pjx = new CGI::Ajax( 'JSFUNC' => \\&PERLFUNC );\n\nThis maps a perl subroutine (PERLFUNC) to an automatically generated Javascript function\n(JSFUNC). Next you setup a trigger this function when an event occurs (e.g. \"onClick\"):\n\nonClick=\"JSFUNC(['source1','source2'], ['dest1','dest2']);\"\n\nwhere 'source1', 'dest1', 'source2', 'dest2' are the DIV ids of HTML elements in your page...\n\n<input type=text id=source1>\n<input type=text id=source2>\n<div id=dest1></div>\n<div id=dest2></div>\n\nCGI::Ajax sends the values from source1 and source2 to your Perl subroutine and returns the\nresults to dest1 and dest2.\n\n4 Usage Methods\n1 Standard CGI::Ajax example\nStart by defining a perl subroutine that you want available from javascript. In this case\nwe'll define a subrouting that determines whether or not an input is odd, even, or not a\nnumber (NaN):\n\nuse strict;\nuse CGI::Ajax;\nuse CGI;\n\n\nsub evenoddfunc {\nmy $input = shift;\n\n# see if input is defined\nif ( not defined $input ) {\nreturn(\"input not defined or NaN\");\n}\n\n# see if value is a number (*thanks Randall!*)\nif ( $input !~ /\\A\\d+\\z/ ) {\nreturn(\"input is NaN\");\n}\n\n# got a number, so mod by 2\n$input % 2 == 0 ? return(\"EVEN\") : return(\"ODD\");\n}\n\nAlternatively, we could have used coderefs to associate an exported name...\n\nmy $evenoddfunc = sub {\n# exactly the same as in the above subroutine\n};\n\nNext we define a function to generate the web page - this can be done many different ways,\nand can also be defined as an anonymous sub. The only requirement is that the sub send back\nthe html of the page. You can do this via a string containing the html, or from a coderef\nthat returns the html, or from a function (as shown here)...\n\nsub ShowHTML {\nmy $html = <<EOT;\n<HTML>\n<HEAD><title>CGI::Ajax Example</title>\n</HEAD>\n<BODY>\nEnter a number:&nbsp;\n<input type=\"text\" name=\"somename\" id=\"val1\" size=\"6\"\nOnKeyUp=\"evenodd( ['val1'], ['resultdiv'] );\">\n<br>\n<hr>\n<div id=\"resultdiv\">\n</div>\n</BODY>\n</HTML>\nEOT\nreturn $html;\n}\n\nThe exported Perl subrouting is triggered using the \"OnKeyUp\" event handler of the input\nHTML element. The subroutine takes one value from the form, the input element 'val1', and\nreturns the the result to an HTML div element with an id of 'resultdiv'. Sending in the\ninput id in an array format is required to support multiple inputs, and similarly, to output\nmultiple the results, you can use an array for the output divs, but this isn't mandatory -\nas will be explained in the Advanced usage.\n\nNow create a CGI object and a CGI::Ajax object, associating a reference to our subroutine\nwith the name we want available to javascript.\n\nmy $cgi = new CGI();\nmy $pjx = new CGI::Ajax( 'evenodd' => \\&evenoddfunc );\n\nAnd if we used a coderef, it would look like this...\n\nmy $pjx = new CGI::Ajax( 'evenodd' => $evenoddfunc );\n\nNow we're ready to print the output page; we send in the cgi object and the HTML-generating\nfunction.\n\nprint $pjx->buildhtml($cgi,\\&ShowHTML);\n\nCGI::Ajax has support for passing in extra HTML header information to the CGI object. This\ncan be accomplished by adding a third argument to the buildhtml() call. The argument needs\nto be a hashref containing Key=>value pairs that CGI objects understand:\n\nprint $pjx->buildhtml($cgi,\\&ShowHTML,\n{-charset=>'UTF-8, -expires=>'-1d'});\n\nSee CGI for more header() method options. (CGI.pm, not the Perl6 CGI)\n\nThat's it for the CGI::Ajax standard method. Let's look at something more advanced.\n\n2 Advanced CGI::Ajax example\nLet's say we wanted to have a perl subroutine process multiple values from the HTML page,\nand similarly return multiple values back to distinct divs on the page. This is easy to do,\nand requires no changes to the perl code - you just create it as you would any perl\nsubroutine that works with multiple input values and returns multiple values. The\nsignificant change happens in the event handler javascript in the HTML...\n\nonClick=\"exportedfunc(['input1','input2'],['result1','result2']);\"\n\nHere we associate our javascript function (\"exportedfunc\") with two HTML element ids\n('input1','input2'), and also send in two HTML element ids to place the results in\n('result1','result2').\n\n3 Sending Perl Subroutine Output to a Javascript function\nOccassionally, you might want to have a custom javascript function process the returned\ninformation from your Perl subroutine. This is possible, and the only requierment is that\nyou change your event handler code...\n\nonClick=\"exportedfunc(['input1'],[jsprocessfunc]);\"\n\nIn this scenario, \"jsprocessfunc\" is a javascript function you write to take the returned\nvalue from your Perl subroutine and process the results. *Note that a javascript function is\nnot quoted -- if it were, then CGI::Ajax would look for a HTML element with that id.* Beware\nthat with this usage, you are responsible for distributing the results to the appropriate\nplace on the HTML page. If the exported Perl subroutine returns, e.g. 2 values, then\n\"jsprocessfunc\" would need to process the input by working through an array, or using the\njavascript Function \"arguments\" object.\n\nfunction jsprocessfunc() {\nvar input1 = arguments[0]\nvar input2 = arguments[1];\n// do something and return results, or set HTML divs using\n// innerHTML\ndocument.getElementById('outputdiv').innerHTML = input1;\n}\n\n4 URL/Outside Script CGI::Ajax example\nThere are times when you may want a different script to return content to your page. This\ncould be because you have an existing script already written to perform a particular task,\nor you want to distribute a part of your application to another script. This can be\naccomplished in CGI::Ajax by using a URL in place of a locally-defined Perl subroutine. In\nthis usage, you alter you creation of the CGI::Ajax object to link an exported javascript\nfunction name to a local URL instead of a coderef or a subroutine.\n\nmy $url = 'scripts/otherscript.pl';\nmy $pjx = new CGI::Ajax( 'external' => $url );\n\nThis will work as before in terms of how it is called from you event handler:\n\nonClick=\"external(['input1','input2'],['resultdiv']);\"\n\nThe otherscript.pl will get the values via a CGI object and accessing the 'args' key. The\nvalues of the 'args' key will be an array of everything that was sent into the script.\n\nmy @input = $cgi->params('args');\n$input[0]; # contains first argument\n$input[1]; # contains second argument, etc...\n\nThis is good, but what if you need to send in arguments to the other script which are\ndirectly from the calling Perl script, i.e. you want a calling Perl script's variable to be\nsent, not the value from an HTML element on the page? This is possible using the following\nsyntax:\n\nonClick=\"exportedfunc(['args$input1','args$input2'],\n['resultdiv']);\"\n\nSimilary, if the external script required a constant as input (e.g. \"script.pl?args=42\", you\nwould use this syntax:\n\nonClick=\"exportedfunc(['args42'],['resultdiv']);\"\n\nIn both of the above examples, the result from the external script would get placed into the\n*resultdiv* element on our (the calling script's) page.\n\nIf you are sending more than one argument from an external perl script back to a javascript\nfunction, you will need to split the string (AJAX applications communicate in strings only)\non something. Internally, we use 'pjx', and this string is checked for. If found,\nCGI::Ajax will automatically split it. However, if you don't want to use 'pjx', you can\ndo it yourself:\n\nFor example, from your Perl script, you would...\n\nreturn(\"A|B\"); # join with \"|\"\n\nand then in the javascript function you would have something like...\n\nprocessfunc() {\nvar arr = arguments[0].split(\"|\");\n// arr[0] eq 'A'\n// arr[1] eq 'B'\n}\n\nIn order to rename parameters, in case the outside script needs specifically-named\nparameters and not CGI::Ajax' *'args'* default parameter name, change your event handler\nassociated with an HTML event like this\n\nonClick=\"exportedfunc(['myname$input1','myparam$input2'],\n['resultdiv']);\"\n\nThe URL generated would look like this...\n\n\"script.pl?myname=input1&myparam=input2\"\n\nYou would then retrieve the input in the outside script with this...\n\nmy $p1 = $cgi->params('myname');\nmy $p1 = $cgi->params('myparam');\n\nFinally, what if we need to get a value from our HTML page and we want to send that value to\nan outside script but the outside script requires a named parameter different from *'args'*?\nYou can accomplish this with CGI::Ajax using the getVal() javascript method (which returns\nan array, thus the \"getVal()[0]\" notation):\n\nonClick=\"exportedfunc(['myparam' + getVal('divid')[0]],\n['resultdiv']);\"\n\nThis will get the value of our HTML element with and *id* of *divid*, and submit it to the\nurl attached to *myparam*. So if our exported handler referred to a URI called\n*script/scr.pl*, and the element on our HTML page called *divid* contained the number '42',\nthen the URL would look like this \"script/scr.pl?myparam=42\". The result from this outside\nURL would get placed back into our HTML page in the element *resultdiv*. See the example\nscript that comes with the distribution called *pjxurl.pl* and its associated outside\nscript *convertdegrees.pl* for a working example.\n\nN.B. These examples show the use of outside scripts which are other perl scripts - *but you\nare not limited to Perl*! The outside script could just as easily have been PHP or any other\nCGI script, as long as the return from the other script is just the result, and not addition\nHTML code (like FORM elements, etc).\n\nGET versus POST\nNote that all the examples so far have used the following syntax:\n\nonClick=\"exportedfunc(['input1'],['result1']);\"\n\nThere is an optional third argument to a CGI::Ajax exported function that allows change the\nsubmit method. The above event could also have been coded like this...\n\nonClick=\"exportedfunc(['input1'],['result1'], 'GET');\"\n\nBy default, CGI::Ajax sends a *'GET'* request. If you need it, for example your URL is getting\nway too long, you can easily switch to a *'POST'* request with this syntax...\n\nonClick=\"exportedfunc(['input1'],['result1'], 'POST');\"\n\n*('POST' and 'post' are supported)*\n",
                "subsections": [
                    {
                        "name": "Page Caching",
                        "content": "We have implemented a method to prevent page cacheing from undermining the AJAX methods in a\npage. If you send in an input argument to a CGI::Ajax-exported function called 'NOCACHE', the a\nspecial parameter will get attached to the end or your url with a random number in it. This will\nprevent a browser from caching your request.\n\nonClick=\"exportedfunc(['input1','NOCACHE'],['result1']);\"\n\nThe extra param is called pjxrand, and won't interfere with the order of processing for the rest\nof your parameters.\n\nAlso see the CACHE() method of changing the default cache behavior.\n"
                    }
                ]
            },
            "METHODS": {
                "content": "",
                "subsections": [
                    {
                        "name": "build_html",
                        "content": "Purpose: Associates a cgi obj ($cgi) with pjx object, inserts\njavascript into <HEAD></HEAD> element and constructs\nthe page, or part of the page.  AJAX applications\nare designed to update only the section of the\npage that needs it - the whole page doesn't have\nto be redrawn.  L<CGI::Ajax> applications use the\nbuildhtml() method to take care of this: if the CGI\nparameter C<fname> exists, then the return from the\nL<CGI::Ajax>-exported function is sent to the page.\nOtherwise, the entire page is sent, since without\nan C<fname> param, this has to be the first time\nthe page is being built.\n\nArguments: The CGI object, and either a coderef, or a string\ncontaining html.  Optionally, you can send in a third\nparameter containing information that will get passed\ndirectly to the CGI object header() call.\nReturns: html or updated html (including the header)\nCalled By: originating cgi script\n"
                    },
                    {
                        "name": "show_javascript",
                        "content": "Purpose: builds the text of all the javascript that needs to be\ninserted into the calling scripts html <head> section\nArguments:\nReturns: javascript text\nCalled By: originating web script\nNote: This method is also overridden so when you just print\na CGI::Ajax object it will output all the javascript needed\nfor the web page.\n"
                    },
                    {
                        "name": "register",
                        "content": "Purpose: adds a function name and a code ref to the global coderef\nhash, after the original object was created\nArguments: function name, code reference\nReturns: none\nCalled By: originating web script\n"
                    },
                    {
                        "name": "fname",
                        "content": "Purpose: Overrides the default parameter name used for\npassing an exported function name. Default value\nis \"fname\".\n\nArguments: fname(\"newname\"); # sets the new parameter name\nThe overriden fname should be consistent throughout\nthe entire application. Otherwise results are unpredicted.\n\nReturns: With no parameters fname() returns the current fname name\n\nJSDEBUG()\nPurpose: Show the AJAX URL that is being generated, and stop\ncompression of the generated javascript, both of which can aid\nduring debugging.  If set to 1, then the core js will get\ncompressed, but the user-defined functions will not be\ncompressed.  If set to 2 (or anything greater than 1 or 0),\nthen none of the javascript will get compressed.\n\nArguments: JSDEBUG(0); # turn javascript debugging off\nJSDEBUG(1); # turn javascript debugging on, some javascript compression\nJSDEBUG(2); # turn javascript debugging on, no javascript compresstion\nReturns: prints a link to the url that is being generated automatically by\nthe Ajax object. this is VERY useful for seeing what\nCGI::Ajax is doing. Following the link, will show a page\nwith the output that the page is generating.\n\nCalled By: $pjx->JSDEBUG(1) # where $pjx is a CGI::Ajax object;\n\nDEBUG()\nPurpose: Show debugging information in web server logs\nArguments: DEBUG(0); # turn debugging off (default)\nDEBUG(1); # turn debugging on\nReturns: prints debugging information to the web server logs using\nSTDERR\nCalled By: $pjx->DEBUG(1) # where $pjx is a CGI::Ajax object;\n\nCACHE()\nPurpose: Alter the default result caching behavior.\nArguments: CACHE(0); # effectively the same as having NOCACHE passed in every call\nReturns: A change in the behavior of buildhtml such that the javascript\nproduced will always act as if the NOCACHE argument is passed,\nregardless of its presence.\nCalled By: $pjx->CACHE(0) # where $pjx is a CGI::Ajax object;\n"
                    }
                ]
            },
            "BUGS": {
                "content": "Follow any bugs at our homepage....\n\nhttp://www.perljax.us\n",
                "subsections": []
            },
            "SUPPORT": {
                "content": "Check out the news/discussion/bugs lists at our homepage:\n\nhttp://www.perljax.us\n",
                "subsections": []
            },
            "AUTHORS": {
                "content": "Brian C. Thomas     Brent Pedersen\nCPAN ID: BCT\nbct.x42@gmail.com   bpederse@gmail.com\n\nsignificant contribution by:\nPeter Gordon <peter@pg-consultants.com> # CGI::Application + scripts\nKyraha  http://michael.kyraha.com/      # getVal(), multiple forms\nJan Franczak <jan.franczak@gmail.com>   # CACHE support\nShibi NS                                # use ->isa instead of ->can\n\nothers:\nRENEEB <RENEEB [...] cpan.org>\nstefan.scherer\nRBS\nAndrew\n",
                "subsections": []
            },
            "A NOTE ABOUT THE MODULE NAME": {
                "content": "This module was initiated using the name \"Perljax\", but then registered with CPAN under the WWW\ngroup \"CGI::\", and so became \"CGI::Perljax\". Upon further deliberation, we decided to change\nit's name to CGI::Ajax.\n",
                "subsections": []
            },
            "COPYRIGHT": {
                "content": "This program is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\nThe full text of the license can be found in the LICENSE file included with this module.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "Data::Javascript CGI Class::Accessor\n",
                "subsections": []
            }
        }
    }
}