0

I have this AJAX post script:

$.ajax({ 
  url: '/products',
  data: { product[order_id]:order_id, product[product_id]:product_id, product[count]:count },
  type: 'post',
  success: function(result){
     // $('.resultMessage').text(result);
  }
})

And it gives me this error: Uncaught SyntaxError: Unexpected token [ - how could I fix this?

Xeen
  • 6,955
  • 16
  • 60
  • 111
  • 1
    dupe:http://stackoverflow.com/questions/20277439/how-to-send-an-javascript-array-to-php-via-jquery-ajax – dramzy Jul 25 '15 at 16:43
  • Notice: you can't get value of associative arrays in javascript like this product[product_id] here product_id know as a variable ,quotation or double quotation are required for associative arrays product["product_id"] – Cyrus Raoufi Jul 25 '15 at 17:05

2 Answers2

1

Your data is not valid JSON. Try this:

$.ajax({ 
  url: '/products',
  data: { 
            product: {
                order_id: order_id,
                product_id: product_id,
                count: count
            }
         },
  type: 'post',
  success: function(result){
     // $('.resultMessage').text(result);
  }
})

And you'd access it like this:

var myOrderId = data.product.order_id;
swatkins
  • 13,530
  • 4
  • 46
  • 78
0
product_array = // array with key and value pair.

var productString = JSON.stringify(product_array);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : productString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

and php code as follow

$post_data = json_decode(stripslashes($_POST['data']));

// and using foreach you can get key or value as follow.

foreach ($post_data as $key => $value) {
    echo $key;
    echo $value;
}
Shridhar
  • 339
  • 2
  • 15