Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Questions about combining Perl with jQuery keep coming up, so I'm posting this simple example to be able to refer to it later.

Update:   You can see a running example of the code here. What it does -- displays a grid of numbers, letting you click on any number to see its factors, and tells whether the number is prime or composite. You can also click on the button "Server Info" to invoke the Ajax code which shows the local time of the server.

Update 2:   If you add the line var J = jQuery.noConflict(); to the top of the file "pm.js", it will let you change every '$' in the file to 'J'. I usually do that, especially when generating the jQuery/Javascript code directly from the CGI script, as it doesn't force me to escape '$' everywhere.

Here is the CGI (ie. Perl) code "pm.cgi" which runs on the server:

#!/usr/bin/perl -w # # Simple jQuery example to demonstrate: # # CGI (Perl) + HTML + CSS + Javascript/jQuery + Ajax # # 2013-08-21 golux ## ############### ## Libraries ## ############### use strict; use warnings; use CGI qw{ :standard }; use CGI::Carp qw{ fatalsToBrowser }; ################## ## User-defined ## ################## my $jquery = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min. +js"; my $max = 625; my $ncols = 25; ################## ## Main program ## ################## server_side_ajax(); print_page_header(); print_html_head_section(); print_html_body_section(); ################# ## Subroutines ## ################# sub print_page_header { # Print the HTML header (don't forget TWO newlines!) print "Content-type: text/html\n\n"; } sub print_html_head_section { # Include stylesheet 'pm.css', jQuery library, # and javascript 'pm.js' in the <head> of the HTML. ## print "<head>\n"; print "<link rel='stylesheet' type='text/css' href='pm.css'>\n"; print "<script src='$jquery' type='text/javascript'></script>\n"; print "<script src='pm.js' type='text/javascript'></script>\n"; print "</head>\n"; } sub print_html_body_section { # Create HTML body and show values from 1 - $max ($ncols per row) print "<body>\n"; print "<center>\n"; print "<h1>Click any number to see its factors</h1>\n"; print qq{ <input type="button" value="Server info" onclick="ajax_info()" +> <span id="info"></span><hr> }; print qq{<div id="result"></div><br>\n}; print "<table width='50%'>"; for (my $i = 0; $i < $max; $i++) { (0 == $i % $ncols) and print "<tr>\n"; my $num = $i + 1; my $onclick = qq{onclick="show_factors($num)"}; print qq{<td id="N$num" class="normal data" $onclick>$num\n}; } print "</table>"; print "</center>\n"; print "</body>\n"; } sub server_side_ajax { my $mode = param('mode') || ""; ($mode eq 'info') or return; # If we get here, it's because we were called with 'mode=info' # in the HTML request (via the ajax function 'ajax_info()'). ## print "Content-type: text/html\n\n"; # Never forget the header! my $ltime = localtime(); print "Server local time is $ltime"; exit; }

This is the CSS stylesheet "pm.css":

body { background: #ffcfff; font-family: arial; } .data { border: 1px solid black; text-align: center; cursor: pointer; min-width: 32px; min-height: 32px; width: 32px; height: 32px; } .normal { background: lightgreen; } .composite { background: #3366ff; } .prime { background: deeppink; } .factor { background: yellow; }

And this is the javascript code "pm.js" which the server downloads to the client (in the HTML page created by "pm.cgi"):
// // Note: adding the line: // // var J = jQuery.noConflict(); // // lets you change '$' everywhere in this file to 'J'. // function show_factors(num) { // First reset all data $('.data').each(function() { $("#"+this.id).attr('class', 'normal data'); }); // Then find and show all the factors var nfactors = 0; var factors = ""; for (var i = 1; i < num; i++) { if (0 == num % i) { ++nfactors; if (factors) factors += ", "; factors += i; var tag = "#N" + i; $(tag).removeClass('normal').addClass('factor'); } } // Highlight chosen square with class 'prime' or 'composite' var b_prime = (nfactors > 1)? false: true; var newclass = (b_prime)? 'prime': 'composite'; var tag = "#N" + num; $(tag).removeClass('normal').addClass(newclass); // Finally, explain the results var text; if (1 == num) { text = "The number 1 is neither prime nor composite"; } else if (b_prime) { text = "The number " + num + " is prime"; text += " (Its only factors are 1 and itself)."; } else { text = "The number " + num + " is composite."; text += " It has " + nfactors + " factors besides itself: " + + factors; } $('#result').html(text); } function ajax_info() { $.ajax({ url: "pm.cgi", cache: false, dataType: "text", data: { mode: 'info' }, success: function(result) { ajax_info_result(result); } }); } function ajax_info_result(result) { var text = "The server says: <b>" + result + "</b>"; $('#info').html(text); }
say  substr+lc crypt(qw $i3 SI$),4,5

In reply to Simple example of CGI (Perl) + HTML + CSS + Javascript/jQuery + Ajax by golux

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-24 23:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found