1

My problem: I am sending data to my PHP using jQuery's $.post method. For some reason, data seem undefined.

Let me explain how my code is structured ...

1. I have the following button with an onClick function:

$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 id='deleteID_$data->id' onclick='Delete($data->id, $tableName, $idName)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>";

same code indented for better readablility:

$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 
                id='deleteID_$data->id' 
                onclick='Delete($data->id, $tableName, $idName)' 
                class='btn btn-danger btn-sm btnBorrar'
            >
                <i class='material-icons' value='delete'>delete</i>
            </button>
        </div>
    </div>
";

2. My Delete() function:

function Delete(id, tableName, idName) {
    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {
        
        console.log("First parameter: " + id + "\nSecond parameter: " + tableName + "\nThird parameter: " + idName); // I GET MY FUNCTION PARAMETERS.
        console.log("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id); // I GENERATE MY POST URL CORRECTLY.
            
        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id, function(data) {
            console.log("My data: " + data);
            if(data == 1) {
                console.log("Data OK");
                //$().hide();
            }
            else if (data == '') {
                console.log("Data empty");
            }
            else if (data == null) {
                console.log("Data null");
            }
            else if (data) {
                console.log("Data exist");
            }
            else {
                console.log("Other reasons");
            }
        });
    }
}

3. So you can see what the console.log() returns:

enter image description here

Why is data not defined?

EDIT: This is my full code: (I didn't want to upload the full code so as not to create confusion, I tried to minimize and compress it).

<?php

    use GuzzleHttp\json_decode;
    include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');

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

    $action = $_POST['action'];
    if(empty($action)){
        $GET = get_vars_for_get();
        $action = $GET['action'];
    }
    
    switch($action){

        case 'datosTabla': // OK.

            //print_r($_POST['action']);
            $res = json_decode($_POST['datos']);
            echo json_encode($res, JSON_UNESCAPED_UNICODE);

            break;

        case 'deleteRegistro':
            //die("Hola");
            $tableName = $_POST['tableName']; // Nombre de la tabla de la base de datos (String).
            $id = $_POST['id'];               // ID (int).
            $idName = $_POST['idName'];       // Nombre del campo ID (String).
            
            echo $tableName;

            //echo deleteRegistro($tableName, $id, $idName);
            
            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];
            //$field = json_encode($field);
            
            $idName = $_POST['id'];
            $idName = json_encode($idName);

            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 id='deleteID_$data->id' onclick='Delete($data->id, $tableName, $idName)' 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, idName){
                    if (confirm("¿Estás seguro que deseas borrar el registro con ID " + id + "?") == true) {
                        
                        console.log("First parameter: " + id + "\nSecond parameter: " + tableName + "\nThird parameter: " + idName); // I GET MY DATA CORRECTLY.
                        console.log("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id); // I GET MY DATA CORRECTLY.

                        $.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id, function(data){
                            
                            console.log("Typeof: " + typeof(data));
                            console.log("My data: " + data);
                            console.log("My data: ", data);
                            console.log("[" + data + "]")
                            
                            if(data == 1){
                                console.log("Data OK");
                                //$().hide();
                            }
                            else if (data == ''){
                                console.log("Data empty");
                            }
                            else if (data == null) {
                                console.log("Data null");
                            }
                            else if (data) {
                                console.log("Data exist");
                            }
                            else {
                                console.log("Other reasons");
                            }
                        });
                    }
                }

                $(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;
}
?>
Caín
  • 181
  • 1
  • 10
  • maybe use `console.log(data);` to see if the output is as expected? – DuchyWare Jul 09 '21 at 12:25
  • `data` is not undefined, that's the problem. You have something there. – nitrin0 Jul 09 '21 at 12:26
  • If I try to print data, I only see blank. @DuchyWare – Caín Jul 09 '21 at 12:26
  • @nitrin0 I edited my code and image, check it, my `data` seem empty, right? – Caín Jul 09 '21 at 12:29
  • I am not familiar with jQuery but is `$.post()` the correct method to send parameters via a query string? Shouldn't you use `$get()`? – secan Jul 09 '21 at 12:30
  • @secan Unfortunately I have to use POST :( – Caín Jul 09 '21 at 12:31
  • 1
    _“my data seem empty, right? ”_ - no, it doesn’t, it appears to contain the text `No data`. Because if that was not what your server responded with, then where should that exact text be coming from? It is not contained in your JS code anywhere. – CBroe Jul 09 '21 at 12:36
  • In general: use `console.log("My data: ", data);` to output to the console, don't concatenate. Though in this case you might like to do `console.log("[" + data + "]")` so you can see explicitly what the value is. Or actually debug it properly. – freedomn-m Jul 09 '21 at 12:50
  • Relevant: [jquery $.post](https://api.jquery.com/jquery.post/#jQuery-post-url-data-success-dataType) - `jQuery.post( url [, data ] [, success ] [, dataType ] )` depends on how your service method is defined, but you should be passing the data as the data parameter. So could be your service (not provided) is expecting a POST *`body`* - as you've said it must be a POST, it's likely the data must be in the body, not the url. – freedomn-m Jul 09 '21 at 12:54
  • As noted above, "No data" is not an option in your console.log if/else - please provide the actual relevant code. If `data` was "not defined" then you would get the "Data null" `else`: https://jsfiddle.net/7oj5fy4n/ – freedomn-m Jul 09 '21 at 12:55
  • Try changing your $.post to: `$.post("=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", new { action:deleteRegistro, tabla:tableName, bombre_campo:idName, id:id }, function(data) { console.log("result:", data); });` – freedomn-m Jul 09 '21 at 12:57
  • @freedomn-m Thank you for your efforts. Trying what you said me in your last message, I get `Uncaught ReferenceError: deleteRegistro is not defined`. I will edite my question with my full code – Caín Jul 09 '21 at 13:02
  • My sample was just quickly typed into a comment to give you the *idea* / format of how to provide the data parameter. You really should be able to determine from `deleteRegistro is not defined` that it should be `action:"deleteRegistro"` not just copy+paste then throw your hands in the air! – freedomn-m Jul 09 '21 at 13:06
  • As suggested above, AFAIK, `$_POST['tablename']` does not take it from the URL. It needs to be in the POST body. A php developer should be able to confirm, Quickest I found quickly was a question asking [how to pass POST parameters in the url](https://stackoverflow.com/questions/6210900/how-can-i-pass-post-parameters-in-a-url), which implies that they're not normally picked up. – freedomn-m Jul 09 '21 at 13:09
  • @freedomn-m Hahaha, I don't usually do copy and paste, but I'm saturated xd, sorry. Now I get `Uncaught TypeError: {(intermediate value)(intermediate value)(intermediate value)(intermediate value)(intermediate value)} is not a constructor`. – Caín Jul 09 '21 at 13:17
  • Now that was my bad- remove the `new {` keyword, `$.post(url, { action:"action", tabla:tableName...` – freedomn-m Jul 09 '21 at 13:46
  • Or look at the examples on the jquery $.post page: https://api.jquery.com/jquery.post – freedomn-m Jul 09 '21 at 13:49
  • Try instead `console.log("My data " + (typeof(data) == "undefined" ? "is undefined" : "is the " + typeof(data) + " " + data));` – Devon Jul 09 '21 at 15:00

2 Answers2

0

If you are wanting to get data back, use $.get

$.get("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id, function(result){
    console.log(result);
});
DuchyWare
  • 71
  • 3
  • Unfortunately I have to use POST. I am creating a CRUD table and I have a giant case where the `action` that is sent by `POST` is evaluated. Thanks for your answer! – Caín Jul 09 '21 at 12:30
  • Note that a POST can/will also return a response. There's no need to use GET to "get data back". – freedomn-m Jul 09 '21 at 12:59
0

The URL you gave in the function Delete() is wrong totally,

<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/?action=deleteRegistro&tabla=" + tableName + "&nombre_campo=" + idName + "&id=" + id

this URl works for GET method not post, for posting any content you don't need to put data into URL.

$.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");                                
                }
                if(data != '') console.log("The response is" + data);
                else console.log("There is not response");
            });

Here the function(data, status) is meant for error handing where data is the response from the URL and status is the status of data sent to the URL.

You have to be careful giving conditions if(data == 1) where data is the response from the URL so it isn't Boolean.

It is very important to handle the request at the other hand where the data is posted so do check it once.

For more info on $.post() visit here

Mohammed Khurram
  • 616
  • 1
  • 7
  • 14