0

What I want to do:

  • I'm trying to send data to my server using $.post jQuery shortcut.

What is the problem:

  • My program doesn't enter in my switch case, maybe because my action it isn't sending properly.

What I'm trying to do:

  • I created a table and one of my elements is a button with an onclick JavaScript function: <button onclick='Delete()'></button>.

  • My JavaScript function:

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

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;      
}
?>
3
  • 1
    You've not described what the exact problem is, or your goal. However I can tell you that returning a mix of HTML/JS from the PHP in the manner you are will not be executed. Commented Jul 6, 2021 at 13:14
  • @RoryMcCrossan I added my problem. Sorry! Commented Jul 6, 2021 at 13:17
  • 1
    You should send your action as part of the request body instead of sending it as part of the URL. jQuery's post method api.jquery.com/jquery.post accepts a data property, which you can to pass your action to the server as part of the request body. Something like data: { action: 'deleteRegistro' } Commented Jul 6, 2021 at 13:36

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, thank you for the explanation, I get it. Now, I don't know how to pass my action in my URL to enter in my case ... I have to use POST method
1

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.

1 Comment

Thanks, this works perfectly, but still without enter in my switch case ... Curious ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.