ydo
ydo

Reputation: 65

Parse data from ajax request to json

I'm trying to send data from Ajax to a php page, I can send the data without trouble, however I have issues to access the data from the PHP page.

My ajax code :

 $http({
    method: 'POST',
    url: 'gen/gen_dup.php',
    data: data,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded' 
    }
}).then(function successCallback(response) {
    console.log('Duplicata MB OK', response);
}, function errorCallback(response) {
    console.log('error', response);
});
};

That is my php code :

$data = json_decode(var_dump($_POST), true);

And I'm getting that back from the PHP page :

array(1) { ["{"title":"Monsieur","name":"aaa","address":"zzz","reference":"zzzzzzee","collector":"1"}"]=> string(0) "" } 

When I'm trying to access it with :

echo $data[0]['reference']; // It doesn't work with $data['reference'] either

I get no result. I'm obtaining the same array if I use :

$data = var_dump($_POST);

Which leads me to believe that the Json decoding is not actually doing anything there. Any suggestion ? Thanks.

Upvotes: 1

Views: 82

Answers (1)

ccprog
ccprog

Reputation: 21811

You are using Content-Type: application/x-www-form-urlencoded. You have to serialize your data accordingly for this to work. jQuery.param or AngularJS $httpParamSerializer can do this for you.

Your post doesnt say it explicitely, but $http() looks like AngularJS. In this case:

$http({
    method: 'POST',
    url: 'gen/gen_dup.php',
    data: data,
    transformRequest: $httpParamSerializer //or jQuery.param,
                                           //or $httpParamSerializerJQLike
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded' 
    }
}).then(....

Or you use Content-Type: application/json and not worry about serialization.

Upvotes: 1

Related Questions