I have a javascript function that collects data from some input fields and checkboxes.
I want to send that data to a PHP file and then return some information from a database.
But I have a problem getting the POST data in PHP so here I will only focus on that problem and won't deal with any database.
The data collected in the HTML form is returned in a Javascript object, I convert it to Json using JSON.stringify(data) and I get :
{"motscle":[""],"categories":[1,2,3],"prix":[{"min":0,"max":50},{"min":50,"max":100},{"min":100,"max":200},{"min":200,"max":500},{"min":500,"max":1000},{"min":1000,"max":2000}],"dimensions":{"longueur":"","largeur":"","hauteur":""}}
You can test it on http://jsonformatter.curiousconcept.com/ to see the expanded form and to see it's a valid JSON. So, the problem is not here I thnk.
Then I have an ajax call like that for testing purpose (var theJSON contains the above JSON string) :
$.ajax({
url: 'post.php',
data: theJSON ,
dataType: 'json',
error: function(){
console.log("Error in ajax request");
},
success: function(data)
{
console.log("Success of ajax request");
console.log(data);
}
});
My testing PHP file post.php is like that :
<?php
header('Content-Type: application/json; charset=utf-8');
echo json_encode($_POST);
?>
The ajax call is OK as I get that in the js console :
Success of ajax request
[]
However as you can see I have also a empty array []. I was expecting to get the $_POST content that PHP should have sent me.
I don't know where I'm wrong. Why don't I get the data in $_POST ?
$_GETand see if that isn't empty. If GET is being populated, add the attributetype: "POST"into your ajax call.