javascript - Pass data to CGI script and back with jQuery.ajax -
i'm working jquery.ajax() send html form data perl script on server , return data frontend.
preferably, data should in text/string format. need save variable further use in jquery functions.
i set html code, javascript code , cgi perl script, while javascript working, connection cgi perl script not , error message: "script call not successful".
maybe 1 can tell me mistake is? i'm not sure how return variable perl script server.
since i'm still new both jquery , javascript , haven't worked asynchronous calls before, appreciated.
this code:
the html code: (where user fills form first name , name:
<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="get_names.js"></script> </head> <body> <div id="logincontent" class="container"> <div id="loginresult" style="display:none;"> </div> <form id="loginform" name="loginform" method="post" action=""> <fieldset> <legend>enter information</legend> <p> <label for="firstname">first name</label> <br /> <input type="text" id="firstname" name="firstname" class="text" size="20" /> </p> <p> <label for="name">name</label> <br /> <input type="test" id="name" name="name" class="text" size="20" /> </p> <p> <button type="submit" class="button positive"> login </button> </p> </fieldset> </form> </div> </body> </html>
the javascript code:
$(document).ready(function(){ $("form#loginform").submit(function() { // loginform submitted var firstname = $('#firstname').attr('value'); // first name var name = $('#name').attr('value'); // name if (firstname && name) { // values not empty $.ajax({ type: "post", url: "/cgi-bin/perl_script.cgi", // url of perl script // send firstname , name parameters perl script data: "firstname=" + firstname + "&name=" + name, // script call *not* successful error: function() { alert("script call not successful"); }, // script call successful // perl_data should contain string returned perl script success: function(perl_data){ alert("your name is: " + perl_data) } }); } else { $('div#loginresult').text("enter name"); $('div#loginresult').addclass("error"); } $('div#loginresult').fadein(); return false; }); });
the perl code:
#!/usr/bin/perl -w use cgi; use strict; use warnings; # read cgi params $cgi = cgi->new; $firstname = $cgi->param("firstname"); $name = $cgi->param("name"); $completename = $firstname . $name; print $completename;
the problem in perl program. not compile. not send required http headers. add print $cgi->header('text/plain;charset=utf-8');
or similar , take care encode output appropriate content type.
Comments
Post a Comment