Andre
Andre

Reputation: 839

Submit form using jQuery get response from Perl script

I just need a simple example on how to submit a form to a Perl script and get a simple response back, I think this sample code is missing something, and I can't figure it out. If someone could tell if this is a good way to start or where the issue is, thanks for the help.
Here is what I am using:

The html file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4   /strict.dtd">
<html>
<head>
<title>jQuery.post demo</title>
<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">

// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {

// Stop form from submitting normally
event.preventDefault();

// Get some values from elements on the page:
var $form = $( this ),
namev     = $form.find( "input[name='name']" ).val(),
agev      = $form.find( "input[name='age']" ).val(),
url       = $form.attr( "action" );
alert(url);

// Send the data using post
var posting = $.post( url, { name: namev, age: agev } );

// Put the results in a div
posting.done(function( data ) {

//var content = $( data ).find( "#content" );

$( "#result" ).empty().append( data );

});

});

</script>

</head>
<body>

<p>jQuery.post</p>

<form action="form_1.pl" id="searchForm">
<input type="text" name="name" placeholder="Search...">
<input type="text" name="age">
<input type="submit" value="Search">
</form>

<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>

</body>
</html>

Here is the Perl test file:

#!/usr/bin/perl

use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser);

my $c = new CGI;

print $c->header();

if ('POST' eq $c->request_method && $c->param('name')) {

# yes, parameter exists
# print $c->param('name');
my $name = $c->param('name');
my $age = $c->param('age');

print "<span style='color:red'>Welcome <b>$name</b>. So you're <b>$age</b> years old eh?</span>";

 }else {

  print "--";

 }

Thanks!

Upvotes: 1

Views: 724

Answers (1)

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24063

I wrapped the code with

$( document ).ready(function() { ... });

and now it works like it should.

(Self-answered by Andre in the comments)

Upvotes: 1

Related Questions