sage88
sage88

Reputation: 4574

jQuery AJAX to Perl JSON module decode of data

I need to be able to decode multiple parameters from the data portion of an ajax call to a perl cgi script. I know that everything else is working with my code, but for whatever reason I can't seem to get the decode method of the JSON module to work properly to restore the data from JSON format to parameters again. The data in my jQuery ajax call is set up like this, which is correct.

data: {
    maxRows: 5,
    productName: request.term
}

However, something is wrong with the way that I'm trying to parse it into perl.

my $json = JSON->new->utf8->allow_nonref;
my $json_text = $cgi->param('data');
my $json_array = $json->decode( $json_text );

I know that the correct end result should be an array of hashes. If I can get that far I know I'll be fine. However, my decode line does not work and actually causes the whole script to fail when it's executed.

I have looked around extensively and I just can't figure this out. I'm pretty sure it's some very small tweak.

Am I getting the parameter correctly by using $cgi->param('data') ? Does it end up being named data, or is it something else?

Upvotes: 1

Views: 2491

Answers (2)

simbabque
simbabque

Reputation: 54381

If you send this as an (asyncronous) POST request from jQuery to your Perl script, you need to give it a parameter for CGI to parse. Otherwise you will need to look at the whole body. CGI cannot parse this data thing, becaue it is not in the correct form.

The request's body would have to be in this form for $cgi->param('data') to work:

data=data:{maxRows:5,productName:request.term}

Instead, try using POSTDATA to get the complete body of the HTTP request that was sent to your script.

my $data = $query->param('POSTDATA');
my $json_array = $json->decode( $data );

See the CGI doc for more info. This question might also be helpful: How can I get the entire request body with CGI.pm?

Upvotes: 2

Marcellus
Marcellus

Reputation: 1287

Your JSON data isn't valid. Use JSONLint to validate your data. A correct example of JSON data would be as follows:

{
    "maxRows": 5,
    "productName": "request.term"
}

If you omit the data: key and surround all keys inside the object with quotation marks, you should be fine. The expression request.term isn't allowed outside of a string since it isn't defined.

Edit

Okay, you're using jQuery to send JSON data. Have a look here to see how to correctly send JSON from jQuery via Ajax. Besides, I'd recommend to use FireBug to check what data is posted by jQuery.ajax.

Upvotes: 1

Related Questions