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

Identifying lastclick in JavaScript

javascript events

I need to get the last click arguments.

Retrieving the length of a list after flattening

python list recursion

I've seen a few questions asking about list flattening and I was wondering how to retrieve the length of the flattened list without actually flattening it. My list can be arbitrarily deep.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.