0

I'm trying to append/push an existing array of strings onto existing html form data. Posting manually like this works fine:

$(function () {
    $('#submitForm').submit(function (evt) {
        //prevent the browsers default function
        evt.preventDefault();
        //grab the form and wrap it with jQuery
        var $form = $(this);
        //if client side validation fails, don't do anything
        if (!$form.valid()) return;
        $.ajax({
            type: $form.prop('method'),
            url: $form.prop('action'),
            data: {
                'ListRFID': GetSelectedItems(), 
                'Printer': 'e38911b2-1a2d-e311-be86-c8f7334c3af0',
                'ExtraLine1': ''
            },
            dataType: "json",
            traditional: true,
            success: function (response) {
                document.body.innerHTML = response;
            }
        });
    });
});

If I do the following and replace AJAX's data with it, it does not work. It sends an undefined variable in lieu of ListRFID.

var temp = { 'ListRFID': GetSelectedItems() };
var data = $form.serializeArray();
data.push(temp);
//AJAX data: data,

The following almost works but sends the post data as ListRFID[]: instead of ListRFID:

data: $form.serialize() + '&' + $.param({ 'ListRFID': GetSelectedItems() }),

Anyone know the proper Javascript methods to get this to work? Much appreciated.

Asef Hossini
  • 655
  • 8
  • 11
ktan
  • 83
  • 7

1 Answers1

0

It seems like what you want to do is merge the contents of two or more objects together.

So in your Ajax call data property would be:

data: $.extend( {}, $form.serializeArray(), { 'ListRFID': GetSelectedItems() } ),

Read more here: http://api.jquery.com/jQuery.extend/

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • Opposite problem from before. Now it sends the params as 0:[object Object] 1:[object Object] ListRFID:a797ad3e-7d2f-e311-be87-c8f7334c3af0 ListRFID:a797ad3e-7d2f-e311-be87-c8f7334c3af1 – ktan Oct 08 '13 at 17:30
  • Still doing the same thing :( – ktan Oct 08 '13 at 17:32
  • You have a different problem. You want a data object with keys as the names and values as the values. You need to convert the `.serializeArray()` result, a list of objects into a single object. That is a different question entirely. That question has multiple answers: http://stackoverflow.com/questions/3277655/how-to-convert-jquery-serialize-data-to-json-object – iambriansreed Oct 08 '13 at 17:39
  • Thank you for the help! Your array part works fine but my question also asked how to combine form data with an array. My form data is just a generic form. I solved this by looping through the list and pushing it to the serializeArray() `var data = $form.serializeArray(); var items = GetSelectedItems(); for (var i = 0; i < items.length; i++) { data.push({ name: 'ListRFID', value: items[i] }); }` Then data: data, Thanks a bunch! – ktan Oct 08 '13 at 18:15