Sending arrays with alphanumeric indexes names through ajax

I'm trying to pass an array through jquery ajax call. However, I need to use descriptive indexes on it eg. item["sku"] = 'abc';

If I create a following array:

item[1] = "abc";
item[2] = "def";

and pass it to below ajax call, I get a proper array on the php end

$.ajax({
    type: "POST",
    url: "/ajax/add_to_cart.php",
    data: {items: item},
    success: function(msg){ }
}); 

However, creating array like that

item["sku"] = "abc";
item["title"] = "product";

produces nothing on the php end

Is there a trick to push such array through? I've tried with jquery stringify but this didn't help

Also, I will need to pass 2-dimensional array in similar matter. Is this possible?

Answers


I assume you're creating an Array instance with either the [] literal or new Array(). The data structure you're looking for though is called an Object in JavaScript, they can also be referred to as associative arrays, hashmaps, or dictionaries in other environments. To create and fill an object in JavaScript you can do something like this:

var item = {};
item["sku"] = "abc";
item["title"] = "product";

You may construct and send collected product data like this:

var item = [{sku:"abc", title:"product1"}, {sku:"def", title:"product2"}, {sku:"ghi", title:"product3"}];

$.ajax({          
    type: "POST",
    url: "/ajax/add_to_cart.php",
    data: {items: JSON.stringify(item)},
    dataType: "json",
    success: function(msg){ }
});

json_decode() will help you out on the PHP end:

<?php
    var_dump(json_decode($_REQUEST['items'], true));
?>

You will want to take a hard look at PHP's json_encode() and json_decode() functions: http://php.net/manual/en/function.json-decode.php (truly the whole library will be helpful) as well as jQuery's $.getJSON() and $.post() functions: http://api.jquery.com/jQuery.post/

<?php

$items_array = json_decode( $_REQUEST['items'], true );

foreach ( $items_array as $key=>$value ){
    // $key = 'sku', 'title', etc.
    // $value = 'abc', 'product', etc.
    // $value might include array( 'key'=>'value', 'key'=>'value' ) when multidimensional
}

Need Your Help

Form:has selector does not work on IE

jquery

I am trying to use "form:has" selector which works on Chrome but not on IE.

Should static_cast<Derived *>(Base pointer) give compile time error?

c++ casting

Should static_cast(Base pointer) give compile time error?