dfilkovi
dfilkovi

Reputation: 3081

JavaScript / JQuery array/object problem

$.fn.fieldValues = function(successful)
{
    var values = {};
    this.each(function()
    {
        if(strstr(this.name, '[]', true))
        {
            var tmp = this.name.replace(/\[\]/, '');
            if(typeof values[tmp] == 'undefined') values[tmp] = {};
            var x = 0;
            while(typeof values[tmp][x] != 'undefined') x++;
            values[tmp][x] = $(this).val();
        }
        else values[this.name] = $(this).val();
    });
    return values;
}

problem is I get this array on php side:

array(['tagCloud'] => '[object Object]', ['status'] => 'Active'.....)

Why is tagCloud an object, how can I post a whole associative array to php?

Upvotes: 0

Views: 419

Answers (3)

dano
dano

Reputation: 5630

Sounds like you need SerializeArray instead, which works like Serialize but will make an array of name/value objects.

You should then turn this into a JSON string and pass through to your php process. The php can then deserialize it back into an array of name/value objects and you can use the data however you want.

//build json object
var dataArray = $.makeArray($("form").serializeArray());

then pass through as a post:

// make ajax call to perform rounding
$.ajax({
    url: "/Rounding.aspx/Round/12",
    type: 'POST',
    dataType: 'html',
    data: $.toJSON(dataArray),  <-- call to jQuery plug in
    contentType: 'application/json; charset=utf-8',
    success: doSubmitSuccess
});

Here is a link to the JSON library I use to serialize the data

Upvotes: 1

Roatin Marth
Roatin Marth

Reputation: 24085

It looks like you're re-inventing jQuery.fn.serialize. jQuery handles inputs with "[]" in the name already:

<form>
    <input type="hidden" name="foo[]" value="1" />
    <input type="hidden" name="foo[]" value="2" />
    <input type="hidden" name="foo[]" value="3" />
</form>

<script>
alert(unescape($('form').serialize())) // "foo[]=1&foo[]=2&foo[]=3"
</script>

php will parse that into an array OOTB.

Upvotes: 0

easement
easement

Reputation: 6139

Would encoding it as a json object and then decoding it in php (json_decode) work out?

Upvotes: 1

Related Questions