I have a client-side appliction which submits some data via AJAX POST request (request.open("POST", url, flag)
) to my Perl CGI script.
How do I retrieve this data with Perl and return some other data (AJAX response)?
I have a client-side appliction which submits some data via AJAX POST request (request.open("POST", url, flag)
) to my Perl CGI script.
How do I retrieve this data with Perl and return some other data (AJAX response)?
The same way you would handle any POST request. You need a CGI script at url
that receives the POST and returns whatever the JavaScript is expecting. The only difference from a normal HTML form POST is the Content-Type that you would be receiving and transmitting.
Use the core CGI module. E.g.
use strict;
use warnings;
use CGI;
my $q = CGI->new;
my $foo = $q->param( 'foo' );
print $q->header;
print "You said $foo";
If your app will be large and complex, you may want to investigate one of the Perl web application frameworks, like CGI::Application or Catalyst.
The basic model for CGI scripts is "read from STDIN, write to STDOUT". At the input stage, the environment variable CONTENT_LENGTH
gives the length in bytes of what is to be read from STDIN
. At the output stage, you also need to send basic HTTP headers, which minimally is one line "Content-Type" with a mime type, like text/html
, or text/plain
, etc. plus a blank line:
Content-Type: text/plain
<your data starts here>
In the case of XMLHttpRequest, you completely control the format of the data, so how you parse the input from STDIN is up to you. Similarly you can lie in the mime type, and send whatever you want as a response.
JSON is a nice format for sending data from Perl to JavaScript.