Ajax post serialize() does not include button name and value

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());
});

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);
});

Tags:

Jquery