Cesar Cesar - 6 months ago 22
JSON Question

Is allowed a mixture of POST/JSON data in jQuery Ajax?

I have the following code, in which a client-side call is made to the server via a jQuery AJAX method. The result is retorned in JSON by the server. All works fine, but I find the "replace" needed to parse the data somehow cumbersome and strange, and if I do not supress the "[" and "]" characters, the code simply does not work. Any suggestion on how it could be improved?

Client-side code:

jQuery.ajax({
type: 'POST',
url: 'ajax/cart_update.php?lang=en',
data: {
'id': id ,
'incr' : increment,
'quantity' : jQuery("#quantity_number" + id).val(),
'final_quantity' : final_quantity,
},
success: function(data){
var data = data.replace("[", "");
data = data.replace("]", "");
if(data != ""){
var obj = jQuery.parseJSON(data);
jQuery("#quantity_number" + id).val(obj.quantity);
jQuery("#total" + id).html(obj.price);
} // if
}
});


Server (PHP) code:

... some SQL query...

$value[0]["quantity"] = $row->quantity;
$value[0]["price"] = get_price_product($row->id_product, $row->quantity);

echo json_encode($value);


With the output being a string: [{"quantity": "8", "price": "$1,756.00"}]

Why I need to supress the "[" and "]" characters?

Jai Jai
Answer

Well actually you are trying to have an object out of your json response. That is quite easily getable with iterators like $.each() in jquery and for..in etc with plain js:

You can use this with an iterator like $.each():

jQuery.ajax({
  type: 'POST',
  url: 'ajax/cart_update.php?lang=en',
  //datatype: 'json', // <----add this, this can parse the response as json.
  data: {
    'id': id,
    'incr': increment,
    'quantity': jQuery("#quantity_number" + id).val(),
    'final_quantity': final_quantity,
  },
  success: function(data) {
    if (data != "") {
      var resp = jQuery.parseJSON(data); // You don't have datatype, so this is required.
      jQuery.each(resp, function(i, obj) {
        jQuery("#quantity_number" + id).val(obj.quantity);
        jQuery("#total" + id).html(obj.price);
      });
    } // if
  }
});

If you add datatype: 'json' in the ajax options then you don't have to parse the json string as a valid json. datatype does this automatically so, you don't have to do it explicitly, the way you are doing.

Comments