Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

389
Views
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!

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

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'));
about 4 years ago · Santiago Trujillo Report

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!