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.