I have a problem trying to send some data from a table that I made, I get an error, it says that the update I am doing to the database is correct but the fields are not updated and it sends me this error
parsererror
SyntaxError: Unexpected token I in JSON at position 0
at JSON.parse (<anonymous>)
at n.parseJSON (jquery.min.js:4)
at vc (jquery.min.js:4)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
I really don't know what this error was because when I click on the send button I get this error and the fields are not updated ... this is the scrip I have
<script>
function viewData(){
$.ajax({
url: '../A30.php?p=view',
method: 'GET',
}).done(function(data){
$('tbody').html(data)
tableData()
})
}
function tableData(){
$('#tabledit').Tabledit({
url:'../A30.php',
eventType: 'dblclick',
editButton : true,
deleteButton : false,
columns:{
identifier:[0,'ID'],
editable: [[0,'ID'],[1, 'Empleado'],[5,'Monto']]
},
buttons:{
style: 'width:150px;',
edit:{
class: 'btn btn-sm btn-success' ,
html: '<span class="fa fa-pencil-square-o" ></span> Editar',
action: 'edit'
},
delete:{
class: 'btn btn-sm btn-default',
html: '<span class="glyphicon glyphicon-trash"></span> Trash',
action: 'delete'
},
save:{
class: 'btn btn-sm btn-info',
html: '<span class="fa fa-floppy-o "></span> Guardar'
},
restore:{
class: 'btn btn-sm btn-warning',
html: 'Restore',
action: 'restore'
},
confirm:{
class: 'btn btn-sm btn-danger',
html: 'Confirm'
},
},
onSuccess: function(data, textStatus, jqXHR){
viewData()
},
onFail: function(jqXHR, textStatus, errorThrow){
console.log('onFail(jqXHR, textStatus, errorThrow)');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrow);
},
onAjax: function(action, serialize){
console.log ('onAjax(action, serialize)');
console.log(action);
console.log(serialize);
}
});
}
</script>
here I have the code in php where I receive the variables to send it to my database but it is not sent it only tells me that it has been inserted successfully but in the database they were not updated
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
if ($input['action'] === 'edit') {
$actualizar ="UPDATE sysnom_nomina_det_tmp SET monto='".$input['Monto']."' where ID='".$input['ID']."' AND empleado = '".$input['Empleado']."' AND monto = '".$input['Monto']."' ";
$resul = sqlsrv_query($conexion, $actualizar);
if(!$resul){
echo "Error al Actualizar";
echo $actualizar;
echo $resul;
} else {
echo "Insertado exitosamente......";
echo $resul;
}
}
sqlsrv_close($resul);
echo json_encode($input);
}
I would really appreciate it if you can help me since I don't know what I have wrong
<?php
require ('recursos/conexion.php');
$page = isset($_GET['p'])? $_GET['p'] : ''
; if ($page=='view') {
$sql = "exec sp_sys_nom_autoriza2 'A30',1";
$stmt = sqlsrv_query($conexion, $sql);
$select = "select * from sysnom_nomina_det_tmp where suc = 'A30'";
$stm = sqlsrv_query($conexion, $select);
$totalVU = sqlsrv_num_rows($stm);
while($row = sqlsrv_fetch_array($stm, SQLSRV_FETCH_ASSOC)) {
if ($row['notas'] !== "AHORRO" ) {
if ($row['notas'] !== "PRESTAMO DE AHORRO") {
?>
<tr style="width:1900px" >
<td style="width:141px;"><?php echo $row["ID"]?> </td>
<td style="width:141px;"><?php echo $row["empleado"]?></td>
<td style="width:141px;"><?php echo $row["nombre"]?> </td>
<td style="width:141px;"><?php echo $row["depto"]?> </td>
<td style="width:141px;"><?php echo $row["percepcion"]?></td>
<td style="width:141px;"><?php echo $row["monto"]?></td>
<td style="width:141px;"><?php echo $row["notas"]?> </td>
<?php
$autorizar = rtrim($row['autorizar']);
if ($autorizar == 1) {
echo "<td id='autorizar'><input type ='checkbox' name='checkbox' id='checkbox' value='1' style='width:30px; height:30px;' checked></td>";
}else{
echo "<td id='autorizar'><input type ='checkbox' name='checkbox' id='checkbox' value='1' style='width:30px; height:30px;'></td>";
}
}
}
}
}else{
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
$respone = [
"message"=>"",
"data"=>[]
];
if ($input['action'] === 'edit') {
$actualizar ="UPDATE sysnom_nomina_det_tmp SET monto='".$input['Monto']."' where ID='".$input['ID']."' AND empleado = '".$input['Empleado']."' AND monto = '".$input['Monto']."' ";
// you can use prepeared statetments for sql injection threats
$resul = sqlsrv_query($conexion, $actualizar);
if(!$resul)
$respone["message"] = "Error al Actualizar";
else
$respone["message"] = "Insertado exitosamente......";
}
sqlsrv_close($resul);
$response["data"]["query"] = $actualizar;
$response["data"]["result"] = $resul;
$response["data"]["input"] = $input;
echo json_encode($response);
}
?>
You must use json_encode function for all outputs(also error messages).
try this version :
header('Content-Type: application/json');
$input = filter_input_array(INPUT_POST);
$respone = [
"message"=>"",
"data"=>[]
];
if ($input['action'] === 'edit') {
$actualizar ="UPDATE sysnom_nomina_det_tmp SET monto='".$input['Monto']."' where ID='".$input['ID']."' AND empleado = '".$input['Empleado']."' AND monto = '".$input['Monto']."' ";
// you can use prepeared statetments for sql injection threats
$resul = sqlsrv_query($conexion, $actualizar);
$response["data"]["result"] = $resul;
if(!$resul)
$respone["message"] = "Error al Actualizar";
else
$respone["message"] = "Insertado exitosamente......";
}
sqlsrv_close($resul);
$response["data"]["query"] = $actualizar;
$response["data"]["input"] = $input;
echo json_encode($response);
}
This will work if you send the your json as string. use
JSON.stringify(ur_object here)
Related
I have this table:
<table id="skuTable" role="grid">
<thead>
<th class="skuRow">Orden</th>
<th class="skuRow">Maquina</th>
<th>Fecha Fab.</th>
<th class="skuRow">Norden</th>
<th>Color</th>
<th>Cliente</th>
<th>Metros</th>
<th>Tiempo</th>
<th>Fecha Ent.</th>
<th>Operario</th>
<th class="skuRow">Editar</th>
</thead>
<tbody>
The SQL query:
<?php
$sql = "SELECT DISTINCT Orden, FFab, N_Orden=Ordenes.OF_N_Orden, Color, Client, Metros, Tiempo, FEnt,Operario
FROM ((
Ordenes INNER JOIN VCLIENTE ON VCLIENTE.Clie_codigo = Ordenes.OF_Cod_Cli
) INNER JOIN ARTITTEC ON ARTITTEC.Tec_codigo = Ordenes.OF_Cod_Art
)
INNER JOIN VTiempos ON VTiempos.Of_n_orden= Ordenes.OF_N_Orden
AND Vtiempos.OF_LIN =Ordenes.OF_Lin
ORDER BY Orden asc, Fecha asc";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
?>
I print the results in a row and identify the 3 that I want to take to POST through the function
<tbody role="rowgroup"><tr data-uid="0bc4355b-a2b7-4cf6-9701-192e77ce6d1d" role="row">
<?php foreach ($maquinas as $maquina): ?>
<?php
$cadena2 = $maquina['OF_Color1'];
$cadena = $maquina['Orden'];
$resultado = str_replace("999", " ", $cadena);
$resultado2 = str_replace("BLACK C", "BLACK ", $cadena2);
?>
<td role="gridcell" class="sku_group" id="sku_group-<?php echo intval ($maquina['Orden'])?>"><span style="color: #ff0000"><strong><?php echo $resultado ?></strong></span></td>
<td role="gridcell"><?php echo $maquina['Fecha'];?></td>
<td role="gridcell" class="sku_maquina" id="sku_maquina-<?php echo intval ($maquina['Maquina'])?>"><?php echo $maquina['Maquina'];?></td>
<td role="gridcell"><?php echo utf8_encode ($maquina['Clie_nombre']);?></td>
<td role="gridcell" class="group_id" align="center" id="group_id-<?php echo intval ($maquina['N_Orden'])?>" ><?php echo $maquina['N_Orden']; ?></form></td>
<td role="gridcell" ><?php echo $maquina['Linea']; ?></td>
<td role="gridcell" > <a target="_blank" href="https://clientes.ealbeniz.com/clientes/images/<?php echo $maquina['OF_Cod_Art'];?>.pdf"><?php echo $maquina['OF_Cod_Art']; ?></a></td>
<td role="gridcell" ><?php echo utf8_encode( $maquina['OF_Descripcion']); ?></td>
<td role="gridcell"><?php echo $maquina['Cant'];?></td>
<td role="gridcell"><?php echo $maquina['Metros']; ?></td>
<td role="gridcell" ><?php echo $maquina['OF_Tipo_Papel'];?></td>
<td role="gridcell"><?php echo $maquina['Tec_Tip_stamp']; ?></td>
<td role="gridcell" ><?php echo $maquina['Tec_Ava_stamp'];?></td>
<td role="gridcell" <?php echo ($maquina['repetido']) ? 'style="color: red; font-weight: bold;"' : ''; ?>><?php echo $maquina['Mag']; ?></td>
<td role="gridcell"><?php echo $maquina['OF_Cod_Troq']; ?></td>
<td role="gridcell"><?php echo $maquina['OF_Num_Tintas'];?></td>
<td role="gridcell"><?php echo $resultado2 ?></td>
<td role="gridcell"><?php echo $maquina['OF_Color2'];?></td>
<td role="gridcell"><?php echo $maquina['OF_Color3']; ?></td>
<td role="gridcell"><?php echo $maquina['OF_Color4']; ?></td>
<td role="gridcell"><?php echo $maquina['OF_Color5']; ?></td>
<td role="gridcell"><?php echo $maquina['OF_Color6']; ?></td>
<td role="gridcell"><?php echo $maquina['OF_Color7'];?></td>
<td role="gridcell"><?php echo $maquina['OF_Color8']; ?></td>
<td role="gridcell"><?php echo $maquina['tIMER']; ?></td>
<td role="gridcell"><?php echo $maquina['ESTADO'];?></td>
<td role="gridcell"><input type="button" class="edit" name="edit" value="Edit"></td>
</tr>
<?php endforeach; ?>
</b>
</font>
<?php
?>
</tbody>
</table><div class="k-pager-wrap k-grid-pager k-widget k-floatwrap" data-role="pager"><span class="k-pager-info k-label"></span></div></div>
At the end of php, I add the following function that with the 3 data that must be sent by POST to update41.php to update the data:
// ----- Edit Row -----
$(document).on("click", "#skuTable .edit", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.edit').length === 0;
});
if ($this.val() === 'Edit') {
$this.val('Save');
if($this.id !== '.sku_group') {
tds.prop('contenteditable', true);
}
} else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
var elements = tds;
if (tds.find('input').length > 0) {
elements = tds.find('input');
}
var dict = {};
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
console.log(type);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "group_id":
dict["Group_ID"] = value;
break;
case "sku_group":
dict["SKU Group"] = value;
break;
case "sku_maquina":
dict["SKU Maquina"] = value;
break;
}
})
if (isValid) {
console.log(dict);
$this.val('Edit');
tds.prop('contenteditable', false);
var request = $.ajax({
type: "POST",
url: "update41.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row updated");
} else {
console.log("row failed to updated");
console.log(response);
console.log(textStatus);
console.log(jqXHR);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.log(textStatus);
console.log(jqXHR);
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
} else {
alert(errors);
}
}
});
</script>
update41.php:
<?php
$Orden = $_POST['SKU Group'];
$NOrden = $_POST['Group_ID'];
$Maquina =$_POST['SKU Maquina'];
$host="xxxxx";
$dbName="xxxxx";
$dbUser="xxxxx";
$dbPass="xxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "UPDATE Ordenes SET OF_OrdenOFs = '$Orden' WHERE OF_N_Orden = '$NOrden'";
$stmt = $pdo->prepare($sql);
//$stmt->bindValue('[:SKU Group]', $SKU);
//$stmt->bindValue(':Group_ID', $Group_ID)
$result = $stmt->execute();
echo json_encode($result);
if(!$result) {
echo json_encode(sqlsrv_errors());
}
$sql2 = "UPDATE VTiempos SET Maquina = '$Maquina' WHERE Of_n_orden = '$NOrden'";
$stmt2 = $pdo->prepare($sql2);
//$stmt->bindValue('[:SKU Group]', $SKU);
//$stmt->bindValue(':Group_ID', $Group_ID)
$result2 = $stmt2->execute();
echo json_encode($result2);
if(!$result2) {
echo json_encode(sqlsrv_errors());
}
?>
The following data appears in the console when pressing save:
sku_group
41prueba.php:459 undefined
41prueba.php:459 sku_maquina
41prueba.php:459 undefined
41prueba.php:459 group_id
2141prueba.php:459 undefined
41prueba.php:474 {SKU Group: "", SKU Maquina: "41", Group_ID: "129236"}
VM25655:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (41prueba.php:484)
at c (jquery-1.10.2.min.js:4)
at Object.fireWith [as resolveWith] (jquery-1.10.2.min.js:4)
at k (jquery-1.10.2.min.js:6)
at XMLHttpRequest.r (jquery-1.10.2.min.js:6)
(anonymous) # 41prueba.php:484
c # jquery-1.10.2.min.js:4
fireWith # jquery-1.10.2.min.js:4
k # jquery-1.10.2.min.js:6
r # jquery-1.10.2.min.js:6
XMLHttpRequest.send (async)
send # jquery-1.10.2.min.js:6
ajax # jquery-1.10.2.min.js:6
(anonymous) # 41prueba.php:477
dispatch # jquery-1.10.2.min.js:5
v.handle # jquery-1.10.2.min.js:5
Here it is seen that it takes the fields, from the row in which I have pressed save to put the example of the console:
41prueba.php:474 {SKU Group: "", SKU Maquina: "41", Group_ID: "129236"}
I can't see why it doesn't pass the data to update41.php
Thank you very much and excuse my English
It looks like your elements variable is a collection of inputs, but your HTML might not have any inputs, except one button.
Also, if you want to pass arbitrary data via HTML, the standard way is with the data- attributes, for example, data-type. Passing it through something like class is very limiting (and unclear to anyone who reads the code).
The mistake was that in this part of the function:
case "group_id":
dict["Group_ID"] = value;
break;
case "sku_group":
dict["SKU Group"] = value;
break;
case "sku_maquina":
dict["SKU Maquina"] = value;
break;
SKU Maquina and SKU Group did not have to be separated (No blank space).
The correct thing was (add _):
case "group_id":
dict["Group_ID"] = value;
break;
case "sku_group":
dict["SKU_Group"] = value;
break;
case "sku_maquina":
dict["SKU_Maquina"] = value;
break;
So in update41.php you have to put it the same:
$NOrden = $_POST['Group_ID'];
$Orden = $_POST['SKU_Group'];
$Maquina =$_POST['SKU_Maquina'];
I have the following table:
<table id="skuTable" role="grid">
<thead>
<th class="skuRow">Orden</th>
<th>Fecha Fab.</th>
<th class="skuRow">Norden</th>
<th>Color</th>
<th>Cliente</th>
<th>Metros</th>
<th>Tiempo</th>
<th>Fecha Ent.</th>
<th>Operario</th>
<th class="skuRow">Editar</th>
</thead>
<tbody>
I get the data from the machine 41
<?php
$sql = "SELECT DISTINCT Orden, FFab, N_Orden=Ordenes.OF_N_Orden, Color, Client, Metros, Tiempo, FEnt,Operario
FROM ((
Ordenes INNER JOIN VCLIENTE ON VCLIENTE.Clie_codigo = Ordenes.OF_Cod_Cli
) INNER JOIN ARTITTEC ON ARTITTEC.Tec_codigo = Ordenes.OF_Cod_Art
)
INNER JOIN VTiempos ON VTiempos.Of_n_orden= Ordenes.OF_N_Orden
AND Vtiempos.OF_LIN =Ordenes.OF_Lin
ORDER BY Orden asc, Fecha asc";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
?>
I write the data in the columns
<td class="orden" id="orden-<?= intval($row['Orden']) ?>"><?php echo $row['Orden'] ?></td>
<td role="gridcell"><?php echo $row['FFab']; ?></td>
<td class="norden" align="center" id="norden-<?= intval($row['N_Orden']) ?>"><?php echo $row['N_Orden']; ?></td>
<td role="gridcell"><?php echo $row['Color']; ?></td>
<td role="gridcell"><?php echo $row['Client']; ?></td>
<td role="gridcell"><?php echo $row['Metros']; ?></td>
<td role="gridcell"><?php echo $row['Tiempo']; ?></td>
<td role="gridcell"><?php echo $row['FEnt']; ?></td>
<td role="gridcell"><?php echo $row['Operario']; ?></td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
</tr></b></font>
<?php { ?>
</tbody>
</table>
<div class="k-pager-wrap k-grid-pager k-widget k-floatwrap" data-role="pager">
<span class="k-pager-info k-label"></span>
</div>
JavaScript for the Edit function:
$(document).on("click", "#skuTable .edit", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.edit').length === 0;
});
if ($this.val() === 'Edit') {
$this.val('Save');
if ($this.id !== '.orden') {
tds.prop('contenteditable', true);
}
}
else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
var elements = tds;
if (tds.find('input').length > 0) {
elements = tds.find('input');
}
var dict = {};
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
console.log(type);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "norden":
dict["N_Orden"] = value;
break;
case "orden":
dict["Orden"] = value;
break;
}
})
if (isValid) {
console.log(dict);
$this.val('Edit');
tds.prop('contenteditable', false);
var request = $.ajax({
type: "POST", url: "update.php", data: dict
});
request.done(function (response, textStatus, jqXHR) {
if (JSON.parse(response) == true) {
console.log("row updated");
}
else {
console.log("row failed to updated");
console.log(response);
console.log(textStatus);
console.log(jqXHR);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
// Log the error to the console
console.log(textStatus);
console.log(jqXHR);
console.error("The following error occurred: " + textStatus, errorThrown);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
else {
alert(errors);
}
}
});
Script Update.php:
<?php
$Orden = $_POST['Orden'];
$NOrden = $_POST['NOrden'];
$host = "xxxxxxxxxx";
$dbName = "xxxxx";
$dbUser = "xxxxxxxxxxxxxx";
$dbPass = "xxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=" . $host . ";Database=" . $dbName, $dbUser, $dbPass);
$sql = "UPDATE Ordenes SET OF_OrdenOFs = '$Orden' WHERE OF_N_Orden = '$NOrden'";
$stmt = $pdo->prepare($sql);
//$stmt->bindValue('[:SKU Group]', $SKU);
//$stmt->bindValue(':Group_ID', $Group_ID)
$result = $stmt->execute();
echo json_encode($result);
if (!$result) {
echo json_encode(sqlsrv_errors());
}
?>
Currently when I press the edit button, it lets me edit the Order field and giving save apparently saves it for me. But when refreshing the page, the records appear blank (that is, if there was no data in the database, it continues to leave it blank and if there was a data before, not only does it not change it, but it also deletes it).
What can I be failing at?
During your JavaScript update call you seem to be setting the value you want to update to dict["N_Orden"]. However, in your Update.php you seem to be wanting the value of $_POST['NOrden'] which I don't believe is defined?
I have a really simple ajax request to "send" the ID of an element the user clicks on the webSite. The script is working only on the Web Console (in the Network -> Preview section). This happens in every browser.
here's the code:
AJAX REQUEST
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {
var itemid = event.target.id;
$.ajax({
type: 'post',
//url: "index.php",
data: {'itemid' : itemid},
cache : false,
async : true,
dataType: 'html',
success: function(data) {
alert('success');
},
failure: function(data) {
alert('failure');
}
});
});
</script>
PHP Function
<?php
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo "success";
$itemid = (int)$itemid;
echo $itemid;
} else{
echo "failure";}
?>
Can you help me with this?
Just adding the image to let you understand better.
UPDATED: Here's the full code, hope it's not too confusionary (still a beginner):
I'm getting the response correct but echo json_encode($d); is not printing.
Btw thank you very much for your support :)
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include '../includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n";
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "</script>";
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo "<script type='text/javascript'>\r\n";
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Here is what can work for you. If it does not work then please share your entire code and the response from PHP too.
// jQuery AJAX call should be something like this
$.ajax({
url: 'index.php',
data: {
"itemid": itemid
},
type: "post",
dataType: "json",
success: function(json) {
if(json.success) {
alert("Item ID is " + json.itemid);
} else {
alert("Item ID is " + json.itemid);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error :: " + textStatus + " :: " + errorThrown);
}
});
// PHP code can be like this
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo json_encode(['success' => true, 'itemid' => $itemid]);
} else {
echo json_encode(['success' => false, 'itemid' => 'Not available']);
}
Consider the following.
JavaScript
$("[class*='point']").click(function(e) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
PHP
<?php
$d = array();
if(isset($_POST['itemid'])){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
?>
In a lot of cases, it's better to pass JSON data back. It's easier for JavaScript to handle it. So we build an array of data that we want to pass back to AJAX request and encode it as JSON.
When we make the AJAX Post, PHP will result in a Successful response. You're welcome to catch an error, this would happen with 400 or 500 Status result from the PHP call. You can also see this in your Web Console.
We're going to get a JSON Object back from PHP, either:
{
result: "success",
itemid: 2
}
Or:
{
result: "error",
error: "'itemid' was not set."
}
In JavaScript, we can use dot notation to access the elements of the object. You can also access it like this:
if(data['result'] == "success")
Dot notation is advised.
Update 1
In your PHP File, you will want a different structure. You're going to have to perform some actions before the HTML is presented to the Browser.
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$itemid = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
$d;
// Connect to SQL
// Query DB for Table Data ...WHERE itemId = '$itemid'
// Store resultset to $d
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once "../grid.asp";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include 'includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n"
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Hope this helps.
Can you please tell me what is wrong with this code? I'm displaying a table using ajax, php and mysql. I'm utilizing the X-editable library for inline editing. My problem is when I click the delete button the swal delete confirm modal pops up, but when I confirm that I want to delete a row/record I get nothing.
I have checked my log file and js console, but I'm not seeing any noticeable errors. I somehow few that the problem is with my code. This is how my code looks. Can you please check and see where I have errors?
This is my script file:
<script>
// this function is used to display the table
function fetch_term(term) {
// body...
if (term != '') {
$.ajax({
url:"includes/ajax/fetch_term_grades.php",
method:"post",
data:{"term":term},
dataType:"text",
success:function(data){
$("#result").html(data);
$('#dataTable').DataTable();
//$('table').attr('id', 'dataTable');
}
});
} else {
$('#result').html('');
}
}
// this is used to delete records
function swal_delete(id){
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
url: 'delete_score.php',
type: 'POST',
data: 'delete='+id,
dataType: 'json'
})
.done(function(response){
swal('Deleted!', response.message, response.status);
fetch_term(term);
})
.fail(function(){
swal('Oops...', 'Something went wrong with ajax !', 'error');
});
});
},
allowOutsideClick: false
});
}
$(document).ready(function() {
var term = $('#term').val();
fetch_term(term);
$('#term').on('change', function() {
var changeTermVal = $('#term').val();
fetch_term(changeTermVal);
});
$(document).on('click', '#delete_score', function(event) {
/* Act on the event */
var id = $(this).data('id');
swal_delete(id);
event.preventDefault();
});
});
</script>
This is the file that returns the table to be display(fetch_term_grades.php)
<?php
$term = mysqli_escape_string($connection, $_POST['term']);
$result = term_select_all($term);
$output = '';
if (mysqli_num_rows($result) > 0) {
# code...
$output .= '<table class="table table-bordered" id="dataTable">
<thead>
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Class</th>
<th>Score</th>
<th>Action</th>
</tr>
</thead>';
$output .= '<tbody>';
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tr>';
$output .= '<td>'.$row["first_name"]." ".$row["middle_name"]." ".$row["surname"].'</td>';
$output .= '<td>'.$row["subject_name"].'</td>';
$output .= '<td>'.$row["class_name"].'</td>';
$output .= '<td>'.$row["score"].'</td>';
$output .= '<td>';
$output .= '<a class="btn btn-info btn-sm" href="edit_grade.php?student='.$row["id"].'" data-target="#scoreModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">';
$output .= '<i class="fa fa-edit"></i>';
$output .= '</a>';
$output .= ' ';
$output .= '<a class="btn btn-danger btn-sm" id="delete_score" data-id="'.$row["id"].'" href="javascript:void(0)">';
$output .= '<i class="fa fa-trash"></i>';
$output .= '</a>';
$output .= '</td>';
$output .= '</tr>';
}
$output .= '</tbody>';
$output .= '</table>';
echo $output;
} else {
echo "Data not found";
}
?>
This is the file that is used to delete records.
<?php
$response = array();
$id = intval($_POST['delete']);
var_dump($id);
$sql = "DELETE from period_one WHERE id = {$id} LIMIT 1 ";
$result = mysqli_query($connection, $sql);
if($result && mysqli_affected_rows($connection) == 1){
$response['status'] = 'success';
$response['message'] = 'Product Deleted Successfully ...';
}
else {
$response['status'] = 'error';
$response['message'] = 'Unable to delete product ...';
}
echo json_encode($response);
?>
I am attempting to create a setInterval function to check for new comments, select and post them. So far, it is 'sort-of' working, but not how I want it to. What it is doing is every three seconds re-posting all of my comments instead of just refreshing them.
What am I doing wrong for this to not just refresh the comments?
HTML
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
AJAX
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
$('#comment-container').prepend(data);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 300);
PHP
$user = new User();
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
echo '<div class="comment-post-box">';
echo $commenter_img;
echo '<div class="comment-post-username">'.$comment_username. '</div>';
echo '<div>'.$comment_date. '</div>';
echo '<div class="comment-post-text">'.$home_comments. '</div>';
echo '</div>';
}
}
}
It's because when you have comments you print new one. What i suggest to do is use JSON to get the comments array, pass an ID to each comment and check if the Id is allready present in the list. that way you only paste new comment, here's an example.:
html
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
<div id="comment-1">bla bla bla</div>
</div>
js
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
var array = JSON.parse(data);
$(array).each(function($value) {
if($('#comment-container').find('#comment-' + $value.id).length == 0) {
$('#comment-container').prepend($value.html);
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 300);
PHP
$user = new User();
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
$html = "";
$html .= '<div class="comment-post-box">';
$html .= $commenter_img;
$html .= '<div class="comment-post-username">'.$comment_username. '</div>';
$html .= '<div>'.$comment_date. '</div>';
$html .= '<div class="comment-post-text">'.$home_comments. '</div>';
$html .= '</div>';
array('id' => $comment_id, 'html' => $html)
}
}
}
For better improvement, i would suggest looking into NodeJs socket for more realtime update. Here's a few link.
Official NodeJs Website
Official SocketIo Website
Chat tutorial with socketIo and Nodejs
Hope it helps!
Nic