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!

1

3 Answers 3

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.

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

Comments

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'));

Comments

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

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.