Valamas - AUS Valamas - AUS - 2 years ago 227
Javascript Question

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

My $.ajax() is not serializing the button name and value.

I have a very simple form. It has a button and a textbox.

<form action="/MyController/MyAction" data-ajax-method="post"
data-ajax-mode="replace" data-ajax-target="#mypartial" id="myform"
<button type="submit" class="positive" name="button" value="click1">
<img src="/Id/Images/Icons/16/enabled/tick.png" title="click1">
<input id="txtBlah" name="txtBlah" type="text" value="hello">

When i call
, the textbox is included in the string but not the button.

Debug.Log($(this).attr('id')); //== 'myform'
Debug.Log("data: " + $(this).serialize()); //== data: txtBlah=hello

I noted during research that with other questions the main reason was a missing name element on the button. I have a name element.

I have also tried making a very simple
<input type="submit" name="mysubmit" />
which did not change anything.

solution i used

var buttonSubmit = (function (e)
var form = $(this).closest('form');
form.attr('data-button-name', $(this).attr('value'));

Answer Source

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) {

    var button = $(;                 
    var result = button.parents('form').serialize() 
        + '&' 
        + encodeURI(button.attr('name'))
        + '='
        + encodeURI(button.attr('value'))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download