Reputation: 331
Imagine I have a CRUD table with a button to delete a register.
What I'm trying to do?
Delete()
(3 variables), they arrive to me to PHP again by means of POST method so that with these data I can make the query and to delete the registry in the Database.The information I want to pass on is as follows:
$data->id // Value example: 1
$tableName // Value example: users_test
$field // Value example: id
My button:
<button onclick='Delete($data->id, $tableName, $field)'>Delete</button>
My Delete
JS function (basically I create a POST request sending an action
to my PHP.
function Delete(id, tableName, field){
$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {
action: "deleteRegistro"
}, function (data, status) {
if (confirm("¿Estás seguro que deseas borrar el registro?") == true) {
if (status === 'error') {
console.log("Not deleted"); // For debugging purpose
} else if (status === 'success') {
console.log("Deleted successfully");
}
}
else {
return false;
}
});
}
My PHP:
switch($_POST['action']){
case 'deleteRegistro':
$id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
$tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
$field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();
break;
}
This if my full code if you need it:
<?php
use GuzzleHttp\json_decode;
include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');
$test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
if ($_GET['action']){
print_a($_GET['action']);
}
switch($_POST['action']){
case 'datosTabla': // OK.
//print_r($_POST['action']);
$res = json_decode($_POST['datos']);
echo json_encode($res, JSON_UNESCAPED_UNICODE);
break;
case 'deleteRegistro':
$id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
$tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
$field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();
break;
case 'showtable': // OK.
$res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
$tableName = $_POST['tableName'];
$field = json_decode($_POST['tableFields'],1)[0];
//print_r($tableName);
//print_r('<br>');
//print_r($campo);
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($data->id, $campo)' 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, campo){
//$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro&tabla=" + tabla + "&nombre_campo=" + campo + "&id=" + id, function(data){
$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {
action: "deleteRegistro"
}, function (data, status) {
if (confirm("¿Estás seguro que deseas borrar el registro?") == true) {
if (status === 'error') {
console.log("Not deleted"); // For debugging purpose
} else if (status === 'success') {
console.log("Deleted successfully");
}
}
else {
return false;
}
});
}
$(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: 267
Reputation: 657
There is also the newer fetch.then
function ajaxpost (divid,var1,var2,var3) {
var pcache = (Math.floor(Math.random() * 100000000) + 1); // this is important to avoid browser cache
var postix = [];
postix["divid"] = encodeURIComponent(divid);
postix["var1"] = encodeURIComponent(var1);
postix["var2"] = encodeURIComponent(var2);
postix["var3"] = encodeURIComponent(var3);
postix["cookies"] = decodeURIComponent(document.cookie); // if you need to send cookies
postix["windowwidth"] = encodeURIComponent($(window).width()); // optional but cool if you need to retrive more that just text....
postix["windowheight"] = encodeURIComponent($(window).height());
// this code will retrieve ALL localStorage and sessionStorage to send to php if you need
for (var i = 0; i < localStorage.length; i++){ postix[localStorage.key(i)] = localStorage.getItem(localStorage.key(i)); }
for (var i = 0; i < sessionStorage.length; i++){ postix[sessionStorage.key(i)] = sessionStorage.getItem(sessionStorage.key(i)); }
fetch("/path_to_php.php?pcache="+pcache, {
method: "POST",
body: JSON.stringify(Object.assign({}, postix)),
headers: {"Content-type": "application/json; charset=UTF-8"}
}).then(function (response) { return response.text(); })
.then(function (html) { $("#"+divid).html(html); })
.catch( err => console.log() );
}
Upvotes: 0
Reputation: 647
May be you should try something, like this:
function Delete(id, tableName, field){
$.post(
"<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/",
{
action: "deleteRegistro"
id: id,
tableName: tableName,
field: field
},
function (success) {....}
)};
Have you forgotten id, tableName and field?
Upvotes: 1