I searched and found several ways to get the submit button name
+ value
sent to the server using jQuery + AJAX. I didn't like them very much...
One of the bests was hunter's solution presented here!
But I wrote another one myself.
I want to share, because it is good, and, as I needed, it works also with forms loaded via ajax (after document.ready):
$(document).on('click', 'form input[type=submit]', function(){
$('<input type="hidden" />').appendTo($(this).parents('form').first()).attr('name', $(this).attr('name')).attr('value', $(this).attr('value'));
});
Simple! When the submit button is clicked, a hidden field is added to the form, using same name
and value
of the submit button.
EDIT: The version below is easier to read. Also, it takes care of removing previously appended hidden fields (in the case of submitting the same form twice, which is perfectly possible when using AJAX).
Improved code:
$(document).on('click', 'form input[type=submit]', function(){
var name = $(this).attr('name');
if (typeof name == 'undefined') return;
var value = $(this).attr('value');
var $form = $(this).parents('form').first();
var $input = $('<input type="hidden" class="temp-hidden" />').attr('name', name).attr('value', value);
$form.find('input.temp-hidden').remove();
$form.append($input);
});