Passing an array with ajax to php

Asked

Viewed 291 times

0

I’m trying to delete multiple records, where I try to get input with Ajax and move on to the PHP.

Printando on the console I can see that I’m picking up the values, but when it comes to going to php, I’m not getting it. Printei no PHP and he won’t even get into:

if (isset($_POST['deleting']) AND $_SERVER['REQUEST_METHOD'] == 'POST')

In the Ajax the code is like this:

$('.delete-form').submit(function(){
    var obj = this;     
    var form = $(obj);
    var submit_btn = $('.delete-form :submit');
    var submit_btn_text = submit_btn.val();
    checkbox = new Array();
        $("input[type=checkbox][name='excluir[]']:checked").each(function(){
            checkbox.push($(this).val());
        });
    console.log(checkbox)
    $.ajax({
        type: "POST",
        data: {
            id: { excluir : checkbox }
        },
        url: form.attr('action'),
        success: function() {
            alert("Houve algum erro ao excluir!");
        },
        success: function( data ) { 
                    alert(data);
            },
        error: function(){
            alert("Houve algum erro ao tentar excluir!");
        }
    });

return false;})

And in the PHP this way:

echo 'antes do if';
if (isset($_POST['deleting']) AND $_SERVER['REQUEST_METHOD'] == 'POST'){
    echo 'depois do if';
    $data = $_POST['excluir'];
    print_r($data);
    foreach($data as $valor){
        $sql = $pdo->prepare("delete FROM client WHERE id = '$valor'");
        $delete = $sql->execute();
        if($delete){
            echo 'OK';
        }
    }
}

Coming by Ajax, he doesn’t even get inside the if of PHP. If I use the PHP without the Ajax, I can delete records.

1 answer

0


It shows up in your script PHP, you are checking if the parameter deleting exists, but I haven’t found him in his Javascript.

Add it.

data: {
    deleting: true,
    id: { excluir : checkbox }
}
  • Thank you very much, that’s exactly what it was, and I’m cracking my head blind.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.