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'];
Related
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 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)
function uppp(id){
var eleme = "uploaded_image"+id;
alert(id);
var name = document.getElementById(id).files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById(id).files[0]);
var f = document.getElementById(id).files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById(id).files[0]);
$.ajax({
url:"http://localhost/wat/admin/category/uppp/"+id,
method:"POST",
data:form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
var x = document.getElementById(eleme);
x.style.color = 'green';
x.innerHTML= "done";
}
});
}
}
this function function is supposed to get the file name from the input control then post the details to a php file which will upload the name in the database. the function is working "selectively"... that is sometimes it works and sometimes it produces the error above... here is the php file from where the file name is taken... please help
while($row = mysqli_fetch_assoc($result)) {
$document_id= $row["document_id"];
$document_description = $row["document_description"];
$output .= "</tr>";
$output .= "<tr> ";
$output .= " <td class='text-center'><p class='nums'>".$count."</p></td>
<td>
<input type='text' name='' class='textdd' value= '".$document_description."' disabled>
</td>
<td word-wrap:break-word'>
<input type='file' name='file' id='$document_id' size='20' required />
</td>
<td>
<button name='$document_id' onclick='uppp(this.name)'>Upload</button>
</td>
<td id='uploaded_image$document_id' color='red'></td>
";
$output .= "</tr>";
$count++;
}
$output .= "<tr> <td> <input type = 'submit' value='Save Documents' class='btn btn-info'> </td> </tr> ";
$output.= " </tbody> </table>";
echo $output;
}
else{
$output .="<td class= 'noresults'> NO documents Found </td> </tr> ";
$output.= " </tbody> </table></form>";
echo $output;
i realized that i had elements from different tables with the same id on the same page . this was because of creating the ids dynamically from 1 to 100. so when the function is passed an id which belongs to two elements that`s when the error occurred.
i realized that when creating ids dynamically for elements the creation process should be as unique as possible
Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.
Question: How can I retrieve location and email of a user when the button is clicked specifically?
Example:
user1, joe doe, [button] -> user1 location, user1#email.com
user2, jay doe, [button] -> user2 location, user2#email.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
$config = array();
$config['base_url'] = base_url() . "controller/pagination";
$total_row = $this->model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 8;
$config['uri_segment'] = 3;
/* $config['use_page_numbers'] = TRUE; */
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = '<span aria-hidden="true">»</span>';
$config['prev_link'] = '<span aria-hidden="true">«</span>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ', $str_links);
// View data according to array.
$this->load->view("view-employees", $data);
}
model.php
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
view.php
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data->username; ?></td>
<td><?php echo $data->name; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data->location;
echo $data->email;
?>
</button>
</td>
</tr>
You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data
Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller
Try like this..
MODEL:
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
return false;
}
View:
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['name']; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data['location'];
echo $data['email'];
?>
</button>
</td>
<?php } ?>
</tr>
When I am using this code it goes in success else condition and show error. But when I refresh the page the record is deleted automatically.
Please suggest me what I can do.
jquery script:
<script>
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = $(this);
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
</script>
View file:
<table style="width:100%" border="1" class="table">
<thead>
<tr>
<th>score Id</th>
<th>student name </th>
<th>subject Name</th>
<th>student marks</th>
<th>Action</th>
</tr>
</thead>
<?php foreach($score as $r): ?>
<tbody>
<tr><td><?php echo $r->score_id; ?></td>
<td><?php echo $r->student_name; ?></td>
<td><?php echo $r->subject_name; ?></td>
<td><?php echo $r->marks; ?></td>
<?php if($status <> 1): ?>
<?php if($admin_id == $r->admin_id): ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>"> Delete</a></td>
<?php endif; ?>
<?php else: ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>" > Delete</a></td>
<?php endif; ?>
</tr>
</tbody>
<?php endforeach; ?>
</table>
Controller file:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = array('error' => 'Error while deleting record');;
return json_encode(array("success" => true));
}
Just change your controller function's last line:
return json_encode(array("success" => true));
to
echo 'Success';
update you controller function as,
public function delete($id) {
...
...
die('Success');
}
I just tried the below condition in script for ajax and it works. I think I am not confirming or not taking response so thats why it continuously going into else condition where error is written.
Hope this will help some one.
MY new script
<script>
$(document).ready(function(){
$(".delete").click(function(event){
var del = confirm("Delete record?");
var href = $(this).attr("href")
var btn = $(this);
if(del == true)
{
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response != "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
}
event.preventDefault();
})
});
</script>
Your ajax return an object so you cant use if (response == "Success") like this.
change code like this:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = 2;
echo 1;
}
if it's true it return 1, so chage ajax like this:
if (parseInt(response)==1)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
I assumed you want hide tr if response is true.
Because you passed it as an array (in javascript it will be converted as an object), the value of the response will be available as response.success. You can check the response object if you write it to the console.
Try this in your ajax method:
success: function(response) {
console.log(response);
if (response.success == true)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
EDIT:
And I suggest you to change the output in your controller's method:
$this->output->set_content_type('application/json')->set_output(json_encode(array("result" => true)));
instead of
return json_encode(array("success" => true));