1

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":"[email protected]",
      "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?

7
  • First things first: simply place a print_r($_POST) or var_dump($_POST) in the PHP page which receives the form submission. Fill out your form, submit and look closely at the data printed to the screen. Familiarize yourself with how form data is posted to scripts, including what gets passed and what doesn't. Commented Jan 18, 2017 at 15:53
  • Add error reporting to the top of your file(s) right after your opening <?php tag error_reporting(E_ALL); ini_set('display_errors', 1); Commented Jan 18, 2017 at 15:54
  • And for now, get rid of the header() Commented Jan 18, 2017 at 15:54
  • How about you don't use JSON.stringify in your javascript, and then in your php use print_r( $_POST)? Commented Jan 18, 2017 at 15:55
  • 1
    Remove this from your AJAX request contentType: 'application/json; charset=utf-8', Commented Jan 18, 2017 at 15:56

2 Answers 2

1

$_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']

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

Comments

0

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"

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.