dapperwaterbuffalo
dapperwaterbuffalo

Reputation: 2748

can I send serialized data along with other variables through JQuery $.post?

so lets say I wanted to essentially do this:

$.post(
    'search_item.php', 
    { 
        serialzed_data, 
        save: form.save.value, 
        is_correct: form.is_correct.value , 
        etc...
    }
)

What is the correct syntax to do so?

many thanks,

EDIT to specify:

lets say I have this:

$.post(
    'search_item.php', 
    { 
        'checks':post_data, 
        'option[]':option, 
        save: form.save.value, 
        item: form.item.value, 
        name: form.i_name.value, 
        desc: form.i_desc.value, 
        text: form.i_text.value 
    },
    function(output)    {
        $('#return2').html(output).show();
    });

now with that current .post I want to add this to it and post them together:

var serialized_data = $('input[name^="checks"]:checked').serialize();

can I do it?

EDIT latest attempt:

var post_data = $('input[name^="checks"]:checked').serialize();

        var data = $.extend({}, post_data, {
        'option[]':option, save: form.save.value, 
        item: form.item.value, 
        name: form.i_name.value, 
        desc: form.i_desc.value, 
        text: form.i_text.value
        });

        $.post('search_item.php', data ,
        function(output)    {
            $('#return2').html(output).show();
        });

Upvotes: 3

Views: 5364

Answers (4)

Parth Gandhi
Parth Gandhi

Reputation: 11

I tried cakar's method and it works beautifully. Use parse_str() in the php file to get the serialized data which is passed from jquery into an array

Upvotes: 1

cakar
cakar

Reputation: 71

data: {
    'formData'         : $("#someForm").serialize(),
    'anotherParameter' : 'someOtherData',
     and so on .... 
},

Upvotes: 1

mpen
mpen

Reputation: 282825

You want to use serializeArray instead (.serialize turns the elements into a string, not an array) like so:

$.post('search_item.php', {
        serializedData: $('input[name^="checks"]:checked').serializeArray(),
        extraVar: value
    },
    function(output)    {
        $('#return2').html(output).show();
    });

The serializedData will be an array, not a 'dictionary', so you'll have to parse it out on the other end.

Actually... .serialize would work just fine too. If you're using PHP on the backend, you'd just have to pass it through parse_str.

or you can make an actual object of key/value pairs and go with Phil's solution using this.

Upvotes: 1

Phil
Phil

Reputation: 164730

Assuming serialzed_data is an object of key -> value properties, use jQuery.extend(), eg

var data = $.extend({}, serialzed_data, {
    save: form.save.value,
    is_correct: form.is_correct.value,
    // etc
});

$.post('search_item.php', data, ...

Upvotes: 4

Related Questions