Trying to use jQuery data to serialize () and add more variables with extension ()

I use $.ajax to submit the form, but I want to add some key-value pairs to the view that are not part of the form inputs. The concatenation technique for these additional parameters works fine, but seems less elegant using $.extend . The problem is that I cannot get the latter to work.

It works:

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

It does not mean:

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

I can see when I check what is served in the case when it works, I have three pairs of key values:

 t:test a:1 b:0.5 

Where t is the name of the input field of one form (text field).

When I use the $.extend function, the check shows the following:

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

My application does not like this request. Is this behavior expected, or can someone indicate what I'm doing wrong?

+4
source share
1 answer

Your problem is that .serialize() only works with jQuery form object and serialized inside .extend() will get the value [object] [object] as the value for your form (this is because this is not the right way to do this. Two solutions:

First solution Clone jQuery form, add elements to it and serialize

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

Second solution Fill the object using the values โ€‹โ€‹of the form, 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) 
+5
source

All Articles