2
\$\begingroup\$

Following a teacher's JavaScript code I intend to delete order's lines with AJAX.

I have tried the code below and it allows the user to delete line by line but for example for the last line it won't delete it.

Function to display order's details:

    public static function showOrderDetails($id){
    $res=DB::execute_sql('select id,idbebida, unidades, pvp from lineaspedido where idpedido=?', array($id));

    if($res){
        $res -> setFetchMode(PDO::FETCH_NAMED);
        $first=true;
        echo '<table class="center"><tr>';
        foreach ($res as $table_row) {
            if($first){ //HEADERS

                foreach ($table_row as $row_index => $row_data) { // titulos campos
                    if($first){ //TO NOT DISPLAY ID
                        $first=false;
                        continue;
                    }
                    echo "<th>$row_index</th>";
                }

            }
            echo '</tr>';


            $first=true;
            foreach ($table_row as $row_data) { // DATA
                if ($first){
                    $idLinea=$row_data;
                    $first=false;
                    echo "<tr id=\"fila$idLinea\">";
                } else{
                    echo "<td>$row_data</td>";
                }
            }

            echo "<td><button onclick=\"deleteLineaPedido($idLinea )\">Borrar</button></td>";
           echo "</tr>";
        }
        echo '</table>';
    }
}

PHP OBJECT to manage JSON:

    <?php
$res = new stdClass();
$res->deleted=false; //Attribute DELETED default false
$res->message=''; //Error message
try{
    $datoscrudos = file_get_contents("php://input"); //READ
    $datos = json_decode($datoscrudos);
    $db = new PDO("sqlite:./datos.db");
    $db->exec('PRAGMA foreign_keys = ON;'); //KEYS
    $sql=$db->prepare('delete FROM lineaspedido WHERE idpedido=?;'); 
    if($sql){
        $sql->execute(array($datos->id));
        if($sql->rowCount()>0){ //NUMBER OF ROWS AFFECTED
           $res->deleted=true; //WHATEVER have been deleted is refreshed
        }
    }
}catch(Exception $e){
   $res->message=$e->getMessage();

header('Content-type: application/json');
echo json_encode($res);

JS function to delete:

function deleteLineaPedido(idLinea){
if(!confirm("Desea borrar la linea de pedido: '"+idLinea+"'")){
    return;
}
var ajax= new XMLHttpRequest();
ajax.onreadystatechange=function(){
    if(this.readyState == 4 && this.status == 200) {
        var res= JSON.parse(this.responseText); //RESULT in JSON 
        if(res.deleted === true){
            var fila=document.querySelector('#fila'+idLinea); //We choose the first and unique row which has whatever ID needed.
            fila.parentNode.removeChild(fila); //We delete the previous row firstly going to its parent node and then deattaching it.
        }
    }
};
ajax.open("post","borrar_linea_Pedido.php",true);
ajax.setRequestHeader("Content-Type","application/json;charset=UTF-8");
ajax.send(JSON.stringify({"id":idLinea})); //Formato {id:identificador de registro a borrar}

Is there a simpler way to achieve this?

PD: The table used 'lieanspedidos' has the following structure:

id          Numeric identifier of every row of order's details
idpedido    Numeric order identifier
idbebida    Numeric drink identifier
unidades    How many drinks have been inserted into that order's row.
PVP         Each drink's price per unit.
\$\endgroup\$
2
\$\begingroup\$

PHP

Variable names, excess variables, logic

When iterating through the rows in showOrderDetails(), the variable $row_index is slightly misleading because that should contain the column name, not an index (typically an integer value):

foreach ($table_row as $row_index => $row_data) { // titulos campos

A better name for that key would be something like $column_name:

foreach ($table_row as $column_name => $column_value) { // titulos campos

But the name $row_index would be appropriate for the key on the outer foreach:

foreach ($res as $row_index => $table_row) {   

Then instead of creating an extra variable called $first, you could utilize $row_index and $column_name to conditionally display the rows and cells.

The first one:

if($first){ //HEADERS

could then be updated to:

if($row_index === 0){ //HEADERS

And then the second one, in the nested loop:

if($first){ //TO NOT DISPLAY ID

Could be changed to:

if($column_name === 'id'){ //TO NOT DISPLAY ID

And the second inner loop could be updated as well:

foreach ($table_row as $row_data) { // DATA
      if ($first){
          continue;

Could be rewritten to add the row if the column name is id:

foreach ($table_row as $column_name => $column_value) { // DATA
    if ($column_name === 'id'){
        $idLinea=$column_value;

And then $first could be eliminated entirely.

Alternatively, the condition in the first nested loop could be negated and then the continue could be eliminated:

if($column_name !== 'id'){ //DO NOT DISPLAY ID
    echo "<th>$column_name</th>";
}

See that all together in this playground example (not connected with Javascript/AJAX requests).

JS

The line to look up the element to remove by id attribute:

var fila=document.querySelector('#fila'+idLinea); //We choose the first and unique row which has whatever ID needed.

Could be changed to use document.getElementById()

  var fila=document.getElementById('fila'+idLinea); //We choose the first and unique row which has whatever ID needed.  

There are a few discussions about which to use:

The general consensus is that getElementById() is quicker than querySelector(). For a small page like this it would likely not be noticeable.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.