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

I have a page that sends JSON data with ajax to a perl file, but I'm a bit lost in retrieving the data. Many posts out there are about generating JSON and sending it, but it's not what I need. So here's the jquery section of the sending page:
$(function(){ // $Date is perl of course var json=jQuery.parseJSON(\'{"DATE":"'.$Date.'"}\'); json["address"]="123 some street"; // other functions generate more fields. and call postM() postM(); function postM(){ $.ajax({ url: "params.pl", type: "GET", processData: false, data: JSON.stringify(json), dataType: "text", async: true, success: function(msg){ alert("perl says: "+msg); } }); // ajax } // postM }); // jquery
and here's all of the param.pl file
#!/usr/bin/perl use strict; use CGI ':standard'; use CGI::Carp "fatalsToBrowser"; my $req=$ENV{QUERY_STRING}; my $i='0'; my $ref=$ENV{HTTP_REFERER}; my $p=param('data'); my $ad=param('address'); my $num_args = $#ARGV + 1; $i++ if $p; $i++ if $ad; $i++ if $req; my $file='json.txt'; open FH,'>',$file; print FH "R:$ref Q:$req A:$ad P:$p G:$ARGV[0] "; close FH; wait; my $fsz= -s $file; print header,"file Sz:$fsz ARGV: $num_args I: $i";
This works ok while jquery sections has type: "GET" but read POST is better way to handle things, though it fails if I change it. Also, when I do get the data, there's a bunch of backslashes and I feel there's got to be a better way. Also note: "processData" is set to false with jquery since I don't know the exact parameter names being transferred. Any help would be appreciated. Thank you perl monk masters.

Replies are listed 'Best First'.
Re: Receiving JSON data with perl
by Anonymous Monk on Aug 10, 2016 at 23:08 UTC

    ... GET ... POST ...

    Use sub DebugCGI to see what your program receives

    Also use the latest CGI.pm

    So here's the jquery section of the sending page:

    Ridiculous :)  var json = { DATE: $Date };

      Yes, ridiculous when I know jquery not better than I should. thanks for the very simple method of assigning date :)

      Also thanks for the info to debug my code. I finally got some results. Apparently i have to use 'keyword' as a param somewhere, but I think I just give up at this point and will resort to one-at-a-time page submissions... going to be a small pain for my customer, but maybe revise it later.

Re: Receiving JSON data with perl
by duyet (Friar) on Aug 11, 2016 at 06:19 UTC
    As you already using CGI you might want to use:
    my $cgi = CGI->new(); my $params = $cgi->Vars();
    to get the parameters sent by ajax and save it in a hash. This works for both GET and POST ...
      I also used your suggestion with the debug subroutine noted above, and as noted in earlier response, started to get more useful results.
      Here's another site hinting at more thoughts, but didn't work out for me:
      iterate-dynamic-array-in-perl-cgi-script