I've been searching and searching, but unfortunately I can't find any answers that relates to my problem.
I'm having trouble to read data that I've sent through jQuery (ajax) in my PHP script.
jQuery:
$('.sendOrder').click(function(){
if (validateForm() == true) {
(function($){
var convertTableToJson = function()
{
var rows = [];
$('table#productOverview tr').each(function(i, n){
var $row = $(n);
rows.push ({
productId: $row.find('td:eq(0)').text(),
product: $row.find('td:eq(1)').text(),
size: $row.find('td:eq(2)').text(),
price: $row.find('td:eq(3)').text(),
quantity: $row.find('td:eq(4)').text(),
});
});
var orderObj = [];
orderObj.push({
name: $("#customerName").val(),
email: $("#customerEmail").val(),
phone: $("#customerPhone").val(),
order: rows
});
return orderObj;
console.log(orderObj);
}
$(function(){
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(convertTableToJson()),
success: function(ret) {
console.log(ret);
}
});
When I'm looking at Chrome it seems to be sent correctly with json:
[
{
"name":"Kristian",
"email":"kristian@example.com",
"phone":"12345678",
"order":[
{
"productId":"Prod #",
"product":"Produkt",
"size":"Str",
"price":"Pris",
"quantity":"Antall"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
}
]
}
]
In my sendData.php I've got it pretty plain:
<?PHP header('Content-Type: application/json');
echo json_encode($_POST);
The return I'm getting are:
[]
What am I doing wrong? What have I forgotten?
$_POST
expects an identifier. In your AJAX you'll have to supply one, for example:
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
// note the change here, adding 'json' as the name or identifier
data: { json: JSON.stringify(convertTableToJson())},
success: function(ret) {
console.log(ret);
}
});
Then you should be able to see the JSON string in $_POST['json']
Solved by using file_get_contents("php://input") instead of post.
I.e
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)) {
$decoded_params = json_decode($json_params);
echo $decoded_params[0]->name;
}
Returned "Kristian"