pk2
pk2

Reputation: 15

How can send array as an data using ajax

Please see attached jsfiddle link, I need to collect data from multiple forms and combined the data as Single data array send it to server(spring mvc controller) to persist using ajax.post

Please let me know best way to do it, will my array be converted to Json by ajax call or I have to do some magic on it.

Thanks http://jsfiddle.net/6jzwR/1/

<form id="form1" name="formone" class="myclass">
    <input type="text" id="txt11" name="txt11" value="name1" />
    <input type="text" id="txt12" name="txt12" value="name2" />
</form>
<form id="form1" name="formtwo" class="myclass">
    <input type="text" id="txt21" name="txt21" value="name3" />
    <input type="text" id="txt22" name="txt22" value="name4" />
</form>
<input type="button" id="button" value="Click Me" />

(function ($) {
    $(document).ready(function () {
        alert("serialize data :" + $('.myclass').length);
        var mydata = null;
        $('#button').on('click', function (e) {

            $('.myclass').each(function () {
                alert("serialize data :" + $(this).serialize());
                if ((mydata === null) || (mydata === undefined)) {
                    mydata = $(this).serializeArray();
                    alert("My data is null");
                } else {
                    mydata = $.merge(mydata, $(this).serializeArray());
                    alert("My data final data after merger " + test);
                }
            });

        });
    });
}(jQuery));

Upvotes: 0

Views: 146

Answers (2)

Musa
Musa

Reputation: 97672

You can put all the forms' data in an array and join them with &

var formdata = []
$('.myclass').each(function(){
    formdata.push($(this).serialize());
});
var data = formdata.join('&');

http://jsfiddle.net/6jzwR/3/

Upvotes: 0

Tony
Tony

Reputation: 7445

Try this:

var array = $('input[type="text"]').map(function() {
    return $(this).val();
}).get();

alert(JSON.stringify(array));

Demo.

Upvotes: 1

Related Questions