My $.ajax() is not serializing the button name and value.
I have a very simple form. It has a button and a textbox.
jQuery's serialize()
is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'))
;
console.log(result);
});
I like @slashingweapon 's approach, but why not even shorter, like this?
$("button.positive").click(function () {
var result = $(this).parents('form').serialize()
+ '&'
+ this.name
+ '='
+ this.value
;
console.log(result);
return false; // prevent default
});
Only if the server generates non-ascii button names or values, it would be like this:
$("button.positive").click(function () {
var result = $(this).parents('form').serialize()
+ '&'
+ encodeURI(this.name)
+ '='
+ encodeURI(this.value)
;
console.log(result);
return false; // prevent default
});
Here's a catch-all solution that will look for an input in the button's containing form. If it exists, it'll set the value, otherwise it will create a hidden input and set its value. This can also be useful if you're not wanting to submit the form immediately.
$(document).on('click', '[name][value]:button', function(evt){
var $button = $(evt.currentTarget),
$input = $button.closest('form').find('input[name="'+$button.attr('name')+'"]');
if(!$input.length){
$input = $('<input>', {
type:'hidden',
name:$button.attr('name')
});
$input.insertAfter($button);
}
$input.val($button.val());
});