t70
t70

Reputation: 43

JQuery .post - $_POST empty

I know ajax calls and $_POST have been around a lot lately, nevertheless i could not find an answer to my current problem.

In my Javascript, I have a two-dimensional data array:

var postData = new Array(new Array());
postData[0]['type'] = 'grid';
postData[0]['data'] = gridData;

I then try to send this array to a PHP script:

function export_report_pdf(postData){
   console.log(postData);

   $.post('/ajax/ExportReportPDF.ajax.php',{data:  JSON.stringify(postData)}, 
   function(postData){
        console.log("Successfully requested report export.");
   });

}

I have tried to receive the array in my PHP script: print_r($_POST); var_dump(json_decode(file_get_contents("php://input")));

but all I get in my $_POST is an empty two-dimensional array. When I do the console.log(postData) in the beginning of my function, the data is there.

I have also checked $_REQUEST and tried removing the JSON.stringify.

Upvotes: 4

Views: 1332

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173642

Your inner variable type should be an object instead of an array, otherwise it won't get serialized properly:

var postData = [];

postData.push({
   type: 'grid',
   data: gridData
});

Upvotes: 5

user229044
user229044

Reputation: 239462

Don't JSON.stringify your post data. jQuery will do that for you, regardless of whether you've done it yourself, so it's winding up double-encoded. If you check your logs, you'll see that, after unencoding the data, PHP has a single POST parameter that is all of your data, JSON encoded.

Your could should look like this:

$.post('/ajax/ExportReportPDF.ajax.php', {data: postData}, ...

Upvotes: 0

Ashish Chopra
Ashish Chopra

Reputation: 1449

have you tried using get instead of post. try that that would atleast ensure that data is getting passed from client to server and problem is with POST request only.

Also when u try GET than check in console if u are getting any error.

Upvotes: 0

Ashish Chopra
Ashish Chopra

Reputation: 1449

function export_report_pdf(postData){
 console.log(postData);

 $.ajax(url:'/ajax/ExportReportPDF.ajax.php',type:'POST',{data: JSON.stringify(postData)}, 
 success:function(postData){
    console.log("Successfully requested report export.");
 });

}

try this. and make sure you have latest jquery included.

Upvotes: -1

Related Questions