Caín
Caín

Reputation: 331

Send data to the server using POST request with jQuery

What I want to do:

What is the problem:

What I'm trying to do:

function Delete(){
    $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro", function(data){
        if(data){
            console.log("Deleteeeed");  
        }
        else {
            console.log("Not deleted :(");
       }
    });
}
switch($_POST['action']){
    case 'deleteRegistro': // NOT OK
        ?>
            <script>
                alert("I'm in deleteRegistro");
            </script>
        <?php 
        
        break;
}

enter image description here

This, should work because I'm passing my action deleteRegistro in my post request to my server (php).

I need some help, what I'm doing wrong?

This is my full code if you want to check it out:


<?php

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

    $test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);

    switch($_POST['action']){
        
        case 'datosTabla': // OK.
            $res = json_decode($_POST['datos']);
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            
            break;
        
        case 'deleteRegistro': // NOT OK
            ?>
            <script>
                alert("I'm in deleteRegistro");
            </script>
            <?php 
            break;
            
        case 'showtable': // OK.
            
            $res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
            $tableName = $_POST['tableName'];
            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()' 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);
            
            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(){
                    $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro", function(data){
                        if(data){
                            console.log("Deleteeeed");  
                        }
                        else {
                            console.log("Not deleted :(");
                        }
                    });
                }
                
                $(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;      
}
?>

Upvotes: 0

Views: 814

Answers (2)

Mohammed Khurram
Mohammed Khurram

Reputation: 626

You are posting to the file in a wrong way that might be the issue as far as I could understand it.

$.post("URL", {
            action: "deleteRegistro"
        }, function (data, status) {
        //  alert (data + '\n' + "status" + status);
            if (status === 'error') {
                console.log("Not deleted"); // For debugging purpose
            } else if (status === 'success') {
              console.log("Deleted successfully");
            }
        });

Put the correct URl in place of "URL" No need to change anything in switch case tho.

But even after this you may not see your data in table got deleted, you need to refresh the page.

As you have all these functionalities in single page I suggest you to use hidden form to post the data.

Upvotes: 1

Quentin
Quentin

Reputation: 943568

You are passing the action in the query string, not the request body, so it will be available in $_GET and not $_POST.

The PHP superglobals $_GET and $_POST do not refer (directly) to the request type. They refer to where an HTML form will put data from an input depending on the method attribute.

Any kind of HTTP request can include a query string in the URL and this will be put in the $_GET superglobal.

Not all HTTP requests can have a request body, but many (including POST and PUT) can. PHP will populate $_POST with data in the request body if it is encoded in a format PHP understands and the Content-Type is correct. (PHP might also check the request type and only do this for POST requests, it isn't something I've investigated).

Upvotes: 2

Related Questions