1

I have the following Jquery code that sends a ajax request to add-to-cart.php.

        var productData = {
    "product_id": s_product_id,
    "product_opties": s_product_opties,
    "product_aantal": s_product_aantal
}

productData = JSON.stringify(productData); 

   $.ajax({
     url: 'inc/add-to-cart.php',
     dataType: "json",
     contentType: "application/json; charset=utf-8",
     data: productData,
     type: 'POST',
     success: function(response) {
         alert(response.d);
     },
     error: function(e){
        console.log(e);
     }
  });

Add-to-cart.php:

  <?php
   print $_POST['product_id'];
  ?>

I am having two problems, the first one is that the $_POST['product_id'] does not exists when i ask for it and secondly when the ajax response returns it goes directly to the error: function and not succes function

The console log says:

  [object Object]{readyState: 4, responseText: "<br />  <b>N...", status: 200, statusText: "OK"}

If the status is OK why does it jump to the error: part?

Thanks!

  • Possible duplicate of [Receive JSON POST with PHP](http://stackoverflow.com/questions/18866571/receive-json-post-with-php) – n00dl3 Mar 22 '17 at 13:53

3 Answers3

1

Try with:

...
var productData = {
  'product_id':     s_product_id,
  'product_opties': product_opties,
  'product_aantal': product_aantal,
}

$.ajax({
  url: 'inc/add-to-cart.php',
  dataType: 'json',
  data: productData,
  type: 'POST',
  success: function(response) {
    console.log(response.d);
  },
  error: function(e){
    console.log(e);
  }
});
...

Omitting the AJAX contentType parameter and the part where you stringify your JSON, that's already ready to be sent to your url, so, isn't needed.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
1

Remove the line

productData = JSON.stringify(productData); 

Then do not return HTML <br> ... from add_to_cart.php, you need to return a JSON string created by the PHP function json_encode and NOTHING ELSE.

Like in:

<?php echo json_encode(array('d' => 'value of d'));
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Adder
  • 5,708
  • 1
  • 28
  • 56
0

First: status Code from the Webserver is 200 cause he deliverd an existing site. Second: You dont need to stringify the json object by urself

enno.void
  • 6,242
  • 4
  • 25
  • 42