views:

451

answers:

1

I have an admin page for a store where a user can modify item data. I'm trying to implement something for the admin to add and remove images by dragging them to and from a div.

I can submit the data just fine until I add the "images" object to the mix as follows:

$("#saveButton").click(function() {
    $("form *, button").attr("disabled", "true");
    formData = $("#itemForm").formHash();
    formData["item"] = $("#itemSelector option:selected").val();
    formData["action"] = "save";
    formData["images"] = {};
    $("#otherImages img").each(function(i){
        formData["images"][i] = $(this).attr("src");
    });
    $.ajax({
        type: "POST",
        url: "adminajax.php",
        data: formData
    });
});

Here, the "images" value is submitted as "[object Object]".

I would like to have "images" be an associative array on the server.

One workaround is to simply have several image keys: "image1: source", "image2: source" etc, however, it would really be nice if it could be an object so that I can do a for-each on "images" instead of filtering the key strings.

+2  A: 

Read the documentation on the data option of $.ajax requests:

If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

So your example could be written as:

formData['images'] = $.map($("#otherImages img"), function(i) {
    return $(i).attr("src");
});

Or, if you're using PHP, you would have to do this as the assignment instead:

formData['images[]'] = ...;
Paolo Bergantino
Great, works beautifully.
Shawn J. Goff