Reputation: 2105
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
?
Upvotes: 0
Views: 2601
Reputation: 318182
The default type of an ajax request is GET, either change the ajax
$.ajax({
url: 'post.php',
type : 'POST',
data: theJSON ,
dataType: 'json',
error: function(){
console.log("Error in ajax request");
},
success: function(data)
{
console.log("Success of ajax request");
console.log(data);
}
});
or check GET
echo json_encode($_GET);
Upvotes: 3