Recently I’ve stuck with a problem where $.post does not send information about button which were pressed.
I.e. we have a form with two buttons.
<form method="post" action="/home/index">
<input type='hidden' name='data1' value='value1' />
<button name="button1" type="submit">First</button>
<button name="button2" type="submit">Second</button>
</form>
$(document).ready(function() {
$('#formId').submit(function () {
var f = $(this);
var action = f.attr("action");
var serf = f.serialize();
$.post(action, serf,
//onreturn
function (data) {
//do something here on success
},
'json'
);
return false;
});
});
Without ajax form is posted as following if user pressed First button: data1=value1&button1
But when I use $.post posted form does not contain any information about button: data1=value1
jQuery 1.6.1
The behavior depends on that which button were pressed.
Any help or workaround would be appriciate!
Since you’re stopping the browser’s default behavior, which is what supplies the button value, you’ll have to capture what button was pressed, and add that information to the data you’re posting (your
serfdata). Probably the most reliable way would be to hook theclickevent on the buttons as well as thesubmitevent of the form, and route them all to a central function that does the ajax submission with (or without) a button value (without in the case of a form submitted another way, rather than by pressing one of those buttons).Something along these lines: