July 18, 2010
jQuery submit ajax form with 2 submit buttons
Question by tetris
im trying to achieve the following, in php i have a form like this:
<form method="post" id="form_1" action="php.php">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
the form action file is:
<?php
if( $_POST["sub"]=="add"){ ?>
<script>
alert("")
</script>
<?php echo "ZZZZZZ"; ?>
<?php } ?>
so this means if i press sub with value add an alert prompt will come up, how can i do the same thing(differentiate both submit) but using a Ajax request:
the following code so does not work:
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize()
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html)
}
})
})
})
</script>
</head>
<body>
<div id="1" style="width: 100px;height: 100px;border: 1px solid red"></div>
<form method="post" id="form_1" action="javascript:;">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
</body>
Answer by Pointy
You could put the event handler on the buttons instead of on the form. Get the parameters from the form, and then add a parameter for the button, and post the form. Make sure the handler returns “false”.
$(function() {
$('input[name=sub]').click(function(){
var _data= $('#form_1').serialize() + '&sub=' + $(this).val();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
You have to explicitly add the “sub” parameter because jQuery doesn’t include those when you call “serialize()”.
Answer by Starx
Lots of semicolon missing, see below
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
});
});