Reputation: 4192
I have a form with a submit button like this:
<form action="?edit-form" method="post" class="addEdit">
<input type="submit" name="delete-image" value="Delete Image">
</form>
My jQuery AJAX is:
$.ajax({
url: $('form.addEdit').attr('action'),
type: $('form.addEdit').attr('method'),
data: $('form.addEdit').serialize(),
success: function(html) { }
});
In my PHP, I am unable to pick up that $_POST['delete-image'] isset() eventhough the submit button that sent the form is named "delete-image".
if (isset($_POST['delete-image'])) {
}
"delete-image" should be set since that was the submit button I clicked. Why is PHP not picking up this posted varaible from this AJAX submit?
Upvotes: 0
Views: 1896
Reputation: 13
If you don't want the page to reload when the button is been click then just use the simple way of sending ajax call:
var mydata = $('form.addEdit').serialize();
$.ajax({
type:'POST',
url: 'file.php',
data: mydata,
dataType:'json',
success: function(responseText){
// enter code here
});
}
});
simply having your form without those elements
<form class="addEdit">
<input type="submit" name="delete-image" value="Delete Image">
</form>
Upvotes: 0
Reputation: 714
In jQuery documenation here: http://api.jquery.com/serialize/
Only succesful control are serialized, please see the documentation below:
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
So submit buttn won't serialize through jQuery.serialize() function. The work around is you can add hidden input, and it will serialized.
UPDATE:
You need to change the form submit ajax to bind the button click. and in ajax request you can add the button value manually. Below is my code that is working.
$( "#delImage" ).click(function( event ) {
event.preventDefault();
$form = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
success: function(html) {
console.log(html);
}
});
});
Upvotes: 2