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

Hello, in my code I have 2 tables. The first table is an array of links that tells a user what groups they are in. When a user clicks one of the links (for example group 1), the 2nd table will give the group name the user clicked and information about that group.

My question is how do I store the value from the javascript function in a Perl variable for later use in my code? ($groupName = var text or $groupName = text in caption tag)

#Table 1 print "<TABLE border=22>"; foreach $tmp (@splitarray) { print "<TR>"; $links = "<a href = '#' onclick='testingFunction(this);'>$tmp</a><BR> +"; print "<TD>$links</TD>"; } print "</TR>"; print "</TABLE>"; } print "<BR>"; #Information Table print " <TABLE border=1 cellpadding='10'> <CAPTION id ='demo2'></CAPTION> <TR> <TD>Members of group:</TD> <TD>Jobs that group can do:</TD> </TR> <TR> <TD>Text on the way</TD> <TD>Text on the way</TD> </TR> </TABLE>"; print "<script type='text/javascript'> function testingFunction(link) { var text = link.innerHTML; document.getElementById('demo2').innerHTML = text; }; </script>";

From research I saw people said to use Ajax or a hidden form but when I tried ajax doing:

$.ajax({ type:'POST', url:'testScript.cgi', data:{'text' : text}, success: function(data) { console.log(data); } dataType: 'json' });

it didn't work (but I may have wrote it wrong).

Replies are listed 'Best First'.
Re: How to store the value of a Javascript function as a Perl variable
by Your Mother (Archbishop) on Jun 23, 2014 at 18:01 UTC

    As mentioned, I think the underlying stuff is a bit unclear to you and I would recommend seeking out tutorials. This stuff is pretty easy once you understand it and extremely frustrating and difficult before then. So–

    Here is something to play with to smooth your journey. This is a fully working proto-type which approximates what you want to do. You may need to install Plack, Plack::Builder, JSON, and Template. You should refer to them for early questions about how the code works. The jQuery is hosted at Google; see dev libs. I recommend never (well nearly never) using ids in HTML/JS. It's an easy bad habit to pick up at first but ids are a global for the DOM and they encourage faulty thinking and painting yourself into corners. Try to think in CSS classes and hierarchies, td.group a for example, as in the code.

Re: How to store the value of a Javascript function as a Perl variable
by flexvault (Monsignor) on Jun 23, 2014 at 17:59 UTC

    Welcome coleb1115,

    I am not an expert nor have I used Ajax, but I do use javascript with HTML to validate and populate form fields to be forwarded to Perl via cgi. I believe Ajax is used for continuous communication with a cgi program/script.

    What you want can be done with javascript, by using the 'onClick' in the HTML. For example the following HTML will call a javascript subroutine called 'checkInfo' when the 'Login' button is clicked.

    <INPUT type=submit value=Login name='ULogin' onClick="return checkInfo +();" />

    The 'checkInfo' subroutine should set the fields in the Form for submission to the web server.

    But, I think you could get what you wanted easier with just a drop down box with the info in table 1, that sends to your Perl script the single item selected, and then to generate a new response HTML document with the related contents of table 2 as another drop down box. (google 'select' for examples).

    Whatever your solution, it will take some time before you understand the full picture, but once you understand the relationships, it will be fun to expand and innovate.

    Good Luck...Ed

    "Well done is better than well said." - Benjamin Franklin

      FYI, Ed, “AJAX” simply is an ordinary HTTP transaction, but it is carried-out asynchronously through another connection with the host, with different Content-Type: and so on as appropriate.   It effectively implements a remote procedure-call (RPC) to the host, and every client-side JavaScript library in use today supports it.   On the host side, it is simply an HTTP POST/GET to a URL that is set-aside for this purpose.   On the client, the magic is done using closures, which must be provided both for normal and error responses from the host.   The customary data-transfer format, used for the actual body of the post, is ordinarily JSON or, less commonly, XML, but sometimes it is done just like ordinary form-data.

        HTML is a perfectly valid response, meaning the Content-Type is possibly the same as the page. Ajax can be done synchronously. DELETE and PUT and other methods are acceptable and becoming common because they are preferable and necessary for real REST. Closures are not a requirement. The data transfer is rarely JSON on the way up, where regular url-encoded params are usually used, but often so on the way back.

        A shallow summary with incorrect definitions and muddy use of terms like "RPC" ingrains misimpressions.

      Using the drop down menu option, would I be able to put in my perl script that $groupName = the drop down list selection?

        Try this simple demo
        #!perl use strict; use CGI; use CGI::Carp 'fatalsToBrowser'; # remove for prod my %groupname = ( ''=>'', 1=>'11111', 2=>'22222', 3=>'33333', 4=>'44444', ); my $q = new CGI; my $group = $q->param('group'); print $q->header,$q->start_html('test'); print qq! <form>Select Group <select name="group" onChange="submit()">!; for my $id (sort keys %groupname){ my $sel = ($id eq $group) ? 'SELECTED' : ''; print qq!<option value="$id" $sel>$groupname{$id}</option>!; } print q!</select></form><hr/>!; #Information Table if ($group){ print qq! <table border="1" cellpadding="10" cellspacing="0"> <h3> $groupname{$group} </h3> <tr> <td>Members of group: $group</td> <td>Jobs that group $group can do:</td> </tr> <tr> <td>Text on the way</td> <td>Text on the way</td> </tr> </table>!; } else { print "<h3>SELECT GROUP</h3>"; } print $q->end_html;
        poj
Re: How to store the value of a Javascript function as a Perl variable
by locked_user sundialsvc4 (Abbot) on Jun 23, 2014 at 16:45 UTC

    Without attempting to dumpster-dive into your particular code, you are correct in deducing that your JavaScript function must send an Ajax request to the host, containing the value(s) in question.   I suggest that you spend some time generally surfing the web at this point to get a better understanding of just how AJAX (and the HTTP protocol in-general) actually works.

    A really interesting way to do this is to turn-on the debugging features of your favorite browser, then go to a particular web-site that you know uses AJAX, and actually watch the two parties talking to one another.   When you click a button, the JavaScript actually forms a complete request-packet and sends it asynchronously to a particular web-address that is dedicated to this purpose, receiving a similarly-formatted response in return.   Basically, it is calling a subroutine on the host side and receiving the response generated by it.   (This is the only way that the two sides can share data.)   Then, do the same thing with your own attempt:   look at what (and, whether ...) your JavaScript code is sending, and what the host does in return.   You have to use a debugger for this because the AJAX interactions won’t show-up on the browser screen.

      Along with everything sundialsvc4 said, I would recommend FireFox with the FireBug add-on as my preferred technology for this type of development.


      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      "This is the only way that the two sides can share data."

      No it isn't. If the data being shared is very simple (a few strings or numbers) there's a somewhat easier method: cookies. Javascript is able to manipulate cookies; so are server-side scripts.

      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
Re: How to store the value of a Javascript function as a Perl variable
by locked_user sundialsvc4 (Abbot) on Jun 23, 2014 at 18:41 UTC

    One final comment that I would make, regarding the OP’s proposed design, is that it is probably not a good idea for the GET/POST to refer to, say, “testScript.cgi,” unless this is the name of the entire web-site.   Don’t make the client-side knowledgeable about how the host-side is organized, and particularly, don’t let the JavaScript (nor any “script kiddie”) call whatever it wants to.   Instead, send all requests to a single, fairly-opaque URL (say, “mysite.com/api), sending a JSON-formatted request (including some kind of “request name” parameter), and receiving a similar response.   Success gets a 200 return-code and a JSON packet; Failure gets 500 and a different, but standard, JSON packet.

    For ideas on the server-side, look at RPC::Any::Server.   (Whether you literally use that code or not, carefully observe the approach.)   It is, at its heart-of-hearts, “a remote procedure-call,” and it should be treated as such.   The client may ask the host to do something on its behalf, but should not be permitted to tell the host what to do nor exactly how to do it.

      Failure gets 500 and a different, but standard, JSON packet.

      5xx response codes typically indicate an internal failure of the HTML-server, such as not being able to execute the script. A 4xx error code might be more appropriate, as it indicates that the client made an error in its request. Even better might be a 200 OK (indicating the script was executed successfully, and didn't die) with a custom error status in accordance with the custom protocol in the response.

      Even if you argue you're free to choose any response code you want, consider the situation where someone attempts to debug a seemingly typical 500 error by checking perms, the shebang line, and all the rest of the usual suspects, only to discover that the script is intentionally faking it. Being an expert on turning around legacy software projects (I take that to mean, fixing other people's mistakes), wouldn't you find that incredibly annoying?

      For ideas on the server-side, look at RPC::Any::Server.

      Why are you recommending a module whose one and only release was four years ago and which fails most of its tests? In case you didn't notice, that bug you reported two years ago about that matter hasn't been fixed yet.

      I suggest you take your own advice and "surf the web to get a better understanding of how the HTTP protocol in-general actually works" (it's like when you drive your car to get a better understanding of how combustion engines actually work, right?), because a mere two months ago you were still confusing HTML with HTTP.