anbutechie has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I m using CGI module to create a web page and i m using java script to get the element which is selected. I m able to store the selected value in javascript variable. I need to store the value in perl variable.
sample code

use CGI qw/:standard/;
$JSCRIPT=<<eof;
function testing() { var v=document.getElementById('product').value; }
eof
print header(), start_html(-title=>'Wow!',-script=> $JSCRIPT), start_form, "PRODUCT", popup_menu(-name=>'Product',-id=>'Product',-value=>'1','2', -multiple=>'true',-size=>5,-onChange=>"testing();"), end_form, end_html();


I need to get the value stored in javascript variable (var) to perl variable.

Regards,
Anbarasu

  • Comment on how to store the value of javascript variable to perl variable

Replies are listed 'Best First'.
Re: how to store the value of javascript variable to perl variable
by almut (Canon) on Apr 22, 2009 at 16:02 UTC
    I need to get the value stored in javascript variable (var) to perl variable.

    First, JavaScript is being run client-side in the browser, while the Perl code is being run server-side by the webserver. So, to get the value of a JavaScript variable into a Perl variable, there's no way around somehow sending it to the server with an HTTP request.

    There are many ways this could be achieved in theory (e.g. Ajax)... But before making your life unnecessarily complicated, I'd first think hard about whether you really need to do it that way — in particular, as the selected value of a menu widget (which is what you'd have in your var v here) is being sent to the server anyway, when you submit the form.   Just my 2 cents :)

Re: how to store the value of javascript variable to perl variable
by mr_mischief (Monsignor) on Apr 22, 2009 at 15:58 UTC
    To get the value in the Perl code on the server from the JavaScript code on the client, you'll have to initiate communication from the client back to the server. You can do this by submitting a form or by using XMLHTTPRequest from JavaScript in the client. There's a broad and deep topic called "AJAX" that covers the latter.

    You can find tools to help you with AJAX, like Prototype, Scriptaculous, or jQuery. There are also Perl modules that help with AJAX, among them CGI::AJAX, HTML::Prototype::JS, and JQuery.

Re: how to store the value of javascript variable to perl variable
by roboticus (Chancellor) on Apr 22, 2009 at 19:24 UTC
    anbutechie:

    If you just need to do it when you send your form back, create a hidden text field in your form, and stuff the value into it. Then your perl code can read it from the text box.

    ...roboticus