Marco
Marco

Reputation: 2737

jQuery serializeArray fails

Consider the following:

PHP:

<form id="f-submit" method="post" action="">

    <button class="btn-submit" name="update" type="submit">APPROUVE</button>

</form>

jQuery:

$("button.btn-submit").click(function(event) {
    event.preventDefault();

    var formData = $("#f-submit").serializeArray();
    formData.push({actiontype: "delete"});

    $.ajax({
        type: "POST",
        url: "includes/submit_comment.php",
        data: formData
    }).done(function(data) {

        alert(data);

    }).fail(function(data) {

        alert('Ajax failed.');

    });
});

submit_comment.php:

if (isset($_POST['actiontype'])) {

    echo 'found';

} else {

    echo 'not found';

}

For some reason, i always get 'not found'.

But, when I'm sending the data without serializing, like so,

var formData = ({actiontype: "delete"});

It works!!!

So the problem must be on the serializeArray(), but what is it? I'm going crazy whith this one...

Upvotes: 0

Views: 605

Answers (2)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11131

try this sytax:

formData.push({name: 'actiontype', value: delete});

Upvotes: 1

lorenzorad
lorenzorad

Reputation: 96

serializeArray()produces an object composed by names and values. Have you tried to debug var formData = $("#f-submit").serializeArray();? In your case it should produce no names/values pairs because:

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. Data from file select elements is not serialized. jQuery doc

Thus you have to add a different input from the submit one. Let's check this smart solution: jQuery serializeArray doesn't include the submit button that was clicked

Upvotes: 0

Related Questions