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));
?>

Need Your Help

Config mod_pagespeed for multiple domains

linux apache mod-rewrite centos mod-pagespeed

Is there a way to set multiple domains VirtualHosts with Google Pagespeed module?

Returning unread records using Linq To SQL

linq-to-sql read-unread

I'm not sure how to ask this question, so I'll start with an example of what I'm doing.