Skip to content

Instantly share code, notes, and snippets.

@luciomartinez
Last active December 20, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciomartinez/6145091 to your computer and use it in GitHub Desktop.
Save luciomartinez/6145091 to your computer and use it in GitHub Desktop.
Very simple HTML page that loads dynamical content using jQuery AJAX function calling a Perl script.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<div id="container">Nothing was loaded yet..</div>
<!-- Load jQuery at the end of the rendering -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
type: 'POST',
url: '/cgi-bin/receptor.pl',
dataType: "text",
data: { name: "Lucio", age: 5},
success: function (data) {
$("#container").html(data);
},
fail: function () {
$("#container").html('Error loading information from server.');
}
});
</script>
</body>
</html>
#!/usr/bin/perl
use warnings;
use strict;
# Receive the method and store the information received
#
my $received_string;
my $method = $ENV{'REQUEST_METHOD'};
if ($method eq "GET") {
$received_string = $ENV{'QUERY_STRING'};
} elsif ($method eq "POST") {
read(STDIN, $received_string, $ENV{'CONTENT_LENGTH'});
} else {
die "Method specified not valid.";
}
# Split the string
my %content = process_string($received_string);
# Prepare the output for HTML
print "Content-type: text/html\n\n";
# Display data
print "<p>Method: $method</p>";
print "<p>This is your data before: $received_string</p>";
print "<p>This is your data processed:</p>";
print '<ul>';
print '<li>'."Name: ".$content{name}.'</li>';
print '<li>'."Age: ".$content{age}.'</li>';
foreach my $key (sort keys(%content)) {
print "<li>The $key has value $content{$key}</li>";
}
print '</ul>';
# Thanks to Jason Nugent, 1998
#
# Process a string and return a hash with all the keys and values
sub process_string {
# Split the string and store each member into a new array
my @values = split (/&/, $_[0]);
my %results = ();
# Store each value in the hash
foreach my $pair (@values) {
my ($key, $value) = split (/=/,$pair); # Split when '='
$value =~ tr/+/ /; # Replace the '+' with ' '
$value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
$results{$key} = $value; # store the key in the results hash
}
return %results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment