4

I'm using $.ajax to submit a form, but I want to add some key-value pairs to the submission that are not part of the form inputs. The technique of concatenating these extra parameters works fine but seems less elegant that using $.extend. The trouble is I can't get the latter to work.

This works:

var data = $form.serialize() + "&a=1&b=0.5";

This does not:

var data = $.extend({}, $form.serialize(), {
    a: 1,
    b: 0.5
});

I can see when I inspect what is submitted in the case that works I have three key value pairs:

t:test
a:1
b:0.5

Where t is the name of the single form input field (a text box).

When I use the $.extend function, inspection reveals the following:

0:t
1:=
2:t
3:e
4:s
5:t
a:1
b:0.5

My application doesn't like this request. Is this behaviour to be expected or can somebody point out what I'm doing wrong?

chrisjleu
  • 4,329
  • 7
  • 42
  • 55
  • what does `var data = $.extend($form.serialize(), { a: 1, b: 0.5 });` do for you? – Mark Schultheiss Jun 11 '12 at 20:59
  • I thought `.serialize` always returned a string – Explosion Pills Jun 11 '12 at 21:10
  • @Mark Schultheiss: That seems to ignore whatever is in the form so in fact only `a` and `b` are in the post request and nothing else. I tried swapping them around but that results in the same problem as described in my question. – chrisjleu Jun 11 '12 at 21:12
  • I think this is because extend expects an object not a string so it creates an object for each "object" in the string array of characters, thus extending your original empty object `{}` – Mark Schultheiss Jun 11 '12 at 21:17
  • Answers: http://www.jblotus.com/2011/07/12/combine-serialized-form-post-data-with-arbitrary-object-in-jquery/ and http://stackoverflow.com/questions/6221939/can-i-send-serialized-data-along-with-other-variables-through-jquery-post – J. Bruni Aug 15 '12 at 14:26

1 Answers1

5

Your problem is because .serialize() only works with a jQuery form object and serialize inside a .extend() will get a [object] [object] as value for your form (that because this is not the proper way of do it. I present two solutions:

First Solution Clone the jQuery's form, add items to it and serialize

var $form = $('#form').clone()
          .append('<input name="foo" value="1" />')
          .append('<input name="bar" value="2" />')
          .serialize();

Second Solution Populate an object with the form's values and then parameterize

var data = $(foo:"value1", bar:"value2");
$('form').find(':input').each(function () {
    if (this.name) {
        data[this.name] = this.value;
    }
});

data = $.param(data)
Alwin Kesler
  • 1,450
  • 1
  • 20
  • 41