简体   繁体   中英

How to send a JS object with ajax

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!

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM