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

Hello I have a webpage with an input section that then runs a perl script with the variables from the input section from the page and then returns the results to the same page this is the code for the HTML page
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquer +y.min.js"></script> </head> <body> <div> <input type="text" name="s" placeholder="Search..." id="urlField"> <input type="button" value="Search" id="btnSearch"> </div> <!-- the result of the search will be rendered inside this div --> <div id="result"></div> <p id="content"> Lorem Ipsum </p> <script> $(document).ready(function () { $("#btnSearch").click(function(event) { // Get some values from elements on the page: var term = $("#urlField").val(); perlExecute(term); }); }); function perlExecute(url){ $.ajax({ type: 'POST', url: '/cgi-bin/doma.pl?url='+url, data: { 'url': url }, success: function(res) { alert(res); }, error: function() {alert("did not work");} }); }; </script> </body> </html>
this is the perl script that am calling
#!/usr/bin/perl -w use warnings; use JSON; use CGI; @my_query_string = split(/s=/,$ENV{'QUERY_STRING'}); my $scalar = join( '' , @my_query_string ); my $rec_hash0 = [$scalar]; my $einput = encode_json($rec_hash0); print "Content-type: text/html\n\n"; print "$einput\n";
when i try run the code above I get the alert "did not work" in the apache2 error logs I have the following error
[Tue Mar 01 20:59:32.474858 2016] [cgid:error] [pid 25562] (104)Connec +tion reset by peer: [client 10.2.2.248:53551] AH02550: Failed to flus +h CGI output to client, referer: http://10.2.2.20/1z.html
Am new to Perl can someone help me with getting this to work

Replies are listed 'Best First'.
Re: Run a perl script and return results using AJAX without reloading the page
by tangent (Parson) on Mar 01, 2016 at 19:31 UTC
    This may not solve your problem but as you are returning JSON you need to set that in the header, so instead of:
    print "Content-type: text/html\n\n";
    Try:
    print "Content-type: application/json\n\n";
    Also, you should really get the value of the query string by creating a new CGI object, so your script would be something like this:
    #!/usr/bin/perl use strict; use warnings; use JSON; use CGI; my $cgi = CGI->new(); my $string = $cgi->param('s'); my $json = encode_json( [$string] ); print $cgi->header( -type => 'application/json' ); print $json;
    Update:
    You probably need to modify your Javascript function too:
    function perlExecute(term){ $.ajax({ type: 'POST', url: '/cgi-bin/doma.pl', data: { 's': term }, success: function(res) { alert(res); }, error: function() {alert("did not work");} }); };