1

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.

7
  • If I use $data = json_decode($_POST, true); it doesn't return anything at all Commented Jan 29, 2016 at 20:03
  • Post the result of print_r($_POST); Commented Jan 29, 2016 at 20:03
  • Array ( [{"title":"Monsieur","name":"aaa","address":"zzz","reference":"zzzzzzee","collector":"1"}] => ) Commented Jan 29, 2016 at 20:11
  • it is impossible for your json_encode(var_dump()) to return anything. var_dump has a void return type - it only does output, it can NEVER return anything. Commented Jan 29, 2016 at 20:12
  • 1
    What is the value of data passed to a script? Commented Jan 29, 2016 at 20:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.