Skip to content
Advertisement

Why doesn’t my program enters in my switch case “deleteRegistro” sending and getting with $_POST in PHP?

My problem: I don’t know why, my switch case is doesn’t working properly and I don’t know why if my AJAX status == 'succcess'.

My onClick function is in my button:

$data->acción = "<div class='text-center'><div class='btn-group'><button id='modificar_$data->id' class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button onclick='Delete($data->id, $tableName, $field)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>";

My function:

function Delete(id, tableName, field){
    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {
        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", { 
            action: "deleteRegistro",
            id: id,
            tableName: tableName,
            field: field
        }, function (data, status){
                if (status === 'error') {
                    console.log("Not deleted");
                }
                else if (status === 'success') {
                    console.log("Deleted successfully");                                
                }
            });
    }
}

My switch case:

switch($_POST['action']){
    case 'deleteRegistro':
            
        $id = $_POST['id'];
        $tableName = $_POST['tableName'];
        $field = $_POST['field'];    
        echo "Hello!";
        ?>
            <script>alert("Hello!");</script>
        <?php 
        
        break;
}

As you can see, my AJAX status == 'succcess':

enter image description here

This is my full code if you need to check it:

<?php

    use GuzzleHttpjson_decode;
    include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');

    $test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
    
    if ($_GET['action']){
        print_a($_GET['action']);
    }

    switch($_POST['action']){
        
        case 'datosTabla': // OK.
            
            //print_r($_POST['action']);
            $res = json_decode($_POST['datos']);
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            
            break;
        
        case 'deleteRegistro':
            
            $id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
            $tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
            $field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();
            
            echo "Hello!";
            ?>
                <script>alert("Hello!");</script>
            <?php 
            
            break;
            
        case 'showtable': // OK.

            $res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
            $tableName = $_POST['tableName'];
            $tableName = json_encode($tableName);

            $field = json_decode($_POST['tableFields'],1)[0];
            //print_r($tableName);
            //print_r('<br>');
            //print_r($campo);
            
            foreach ($res as $data){                
                $data->acción = "<div class='text-center'><div class='btn-group'><button id='modificar_$data->id' class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button onclick='Delete($data->id, $tableName, $field)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>"; 
                $resultados['data'][] = $data;
            }           
            
            $resultados = json_encode($resultados); // 7 PROPIEDADES
            
            foreach(json_decode($_POST['tableFields']) as $columnsDB){
                $fields[] = array('data'=>$columnsDB);
            }

            $fields[]['data'] = 'acción';
            $fields = json_encode($fields);
            
?>
            <head>
                <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
            </head>
            
            <div class="container caja">
                <div class="row">
                    <div class="col-lg-12 col-sm-12">
                        <div>
                            <table id="tablaUsuarios" class="table table-striped table-bordered table-condensed hover" style="width:100%" >
                                <thead class="text-center">
                                    <tr>
                                        <?php
                                            foreach (json_decode($_POST['tableFields']) as $columnsTH){
                                                 echo '<th>' . strtoupper($columnsTH) . '</th>';
                                            }
                                            echo '<th>ACCIÓN</th>';
                                        ?>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <script>

                function Delete(id, tableName, field){
                    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {
                        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", { 
                            action: "deleteRegistro",
                            id: id,
                            tableName: tableName,
                            field: field
                        }, function (data, status){
                                if (status === 'error') {
                                    console.log("Not deleted");
                                }
                                else if (status === 'success') {
                                    console.log("Deleted successfully");                                
                                }
                            });
                    }
                }
                    
                $(document).ready(function() {
                    var datos= <?=$resultados?>;
                    var dynamicColumns = <?=$fields?>;
                    datos = JSON.stringify(datos);
                    
                    $('#tablaUsuarios').DataTable({
                        "language": {"url": "https://cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"},
                        "paging": true,
                        "lengthChange": true,
                        "searching": true,
                        "info": true,
                        "autoWidth": true,
                        "scrollX": true,

                        "ajax":{
                            "url": '<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/',
                            "method": 'POST',
                            "data":{action: "datosTabla", datos: datos}
                        },

                        "columns": dynamicColumns
                    });
                })
            </script>
<?php
        break;      
}
?>

Can someone give me a hand? I really don’t understand.

If the status == 'success', it means that the POST request has been sent successfully, so I should go into my case switch and print a “Hello!”.

What am I doing wrong?

Advertisement

Answer

You haven’t mentioned in the question where the switch case is on, I assume its in <?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/" index.php file ok?

So you are posting the data to a php file using Ajax and Ajax successfully posts the data, but how come you can expect that hello to be displayed on the screen?

As I have mentioned in my previous answer the output of the php file where switch case exist will not be displayed, $.post method just posts the data to the file it won’t redirects to the file.

for your need I suggest you to use the hidden form to post the data to the file.

Modified delete function would be..

function Delete(id, tableName, field){
    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {
document.getElementById("postid").value = id;
document.getElementById("postTablename").value = tableName;
document.getElementById("postfield").value = field;
document.forms['deleteform'].submit();
         //Commenting old function
        /*$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", { 
            action: "deleteRegistro",
            id: id,
            tableName: tableName,
            field: field
        }, function (data, status){
                if (status === 'error') {
                    console.log("Not deleted");
                }
                else if (status === 'success') {
                    console.log("Deleted successfully");                                
                }
            });*/
    }
}

Now add a form deleteform in html code note:- add before you use this script for function Delete()

<form name="deleteform" action="<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/" method="post">
<input type="hidden" id="postid" name="id" value="">
<input type="hidden" id="postTablename" name="Tablename" value="">
<input type="hidden" id="postfield" name="field" value="">
</form> 

After this form get submit you will be entering to your php file in the given URL, here you can do whatever you want play with the data you got from post method.

If you don’t want to redirect to you php file containing switch case just display data you got from the page.

function Delete(id, tableName, field){
    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {
        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", { 
            action: "deleteRegistro",
            id: id,
            tableName: tableName,
            field: field
        }, function (data, status){
                if (status === 'error') {
                    console.log("Not deleted");
                }
                else if (status === 'success') {
                    console.log("Deleted successfully" + "This is the response:- " + data);                                
                }
            });
    }
}

Now you can see what is the response of the file in console, in your case it should show you hello as you haven’t echoed anything else.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement