views:

240

answers:

4

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)?

+4  A: 

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.

cjm
I know how it works, but I'm not very familiar with Perl, so I'm asking. "The same way you would handle any POST request" - I have no idea how to handle POST request using Perl, this was my question.
Peterim
@Peterim, then you should give more details about what you're trying to accomplish. There's lots of ways to do it, and it's hard to know which to recommend without knowing more about your situation.
cjm
+1  A: 

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.

friedo
This is just bad advice. There is no guarantee that the data from XMLHttpRequest is formatted as the output from an HTML form.
Kinopiko
True, there's no guarantee, but all Ajax libraries use form encoding by default, unless you compose your own post data string. Given that the OP did not state anything to the contrary, it's reasonable to assume the default behavior.
friedo
OK, but your answer doesn't have any caveats about where it might or might not work.
Kinopiko
A: 

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.

Kinopiko
A: 
 use CGI;
 my $q = CGI->new;
 my $xml = $q->param('POSTDATA');
janet