Update SQL Server data from HTML table - javascript

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?

Related

Update sql base through html table

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'];

How to insert multiple rows in php with two data is not in the table?

I have a problem inserting the multiple row from my table to my database. Ill show picture of my UI.
https://i.stack.imgur.com/1okJB.png
There are 5 column that I will insert into my database Barcode,Description and QTY is in the table that I want to insert and the two data is outside the table,or not on the table e.g username and customer_id. Its printed on the other part of my UI.
I tried this ajax code but nothing happen.
$(document).on('click','.Enter',function(e){
var user = [];
var product = [];
var customer = [];
var quantity = [];
$('input .user').each(function(){
user.push($(this).text());
});
$('tableData tr td .barcode').each(function(){
product.push($(this).text());
});
$('select .customer_id').each(function(){
customer.push($(this).text());
});
$('tableData tr td .qty').each(function(){
quantity.push($(this).text());
});
$.ajax({
url:"insert_sales.php",
method:"POST",
data:{user:user, product:product, customer:customer, quantity:quantity},
success: function(data){
alert(user[0]);
},
})
});
This is part of my HTML file.
<input type="hidden" name="user" value="<?php echo $row['username']; ?>" class="user" />
<select class="customer_id" name="customer" style='cursor:pointer'>
<?php
if(mysqli_num_rows($show)>0){
while ($row = mysqli_fetch_array($show)) {
?>
<option value="<?php echo $row['customer_id']; ?>"><?php echo $row['firstname'];?>
</option>
<table id="table2">
<thead>
<tr class='text-center'>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
This is my insert_product.php file.
if(isset($_POST['user'])){
$user = $_POST['user'];
$product = $_POST['products'];
$customer = $_POST['customer'];
$quantity = $_POST['quantity'];
$query = '';
for($count = 0; $count<count($user); $count++){
$user_clean = mysqli_real_escape_string($db, $user[$count]);
$product_clean = mysqli_real_escape_string($db, $user[$count]);
$customer_clean = mysqli_real_escape_string($db, $user[$count]);
$quantity_clean = mysqli_real_escape_string($db, $user[$count]);
if($user_clean != '' && $product_clean != '' && $customer_clean != '' && $quantity!= ''){
$query = "INSERT INTO sales(username,product_id,customer_id,quantity) VALUES('$user_clean',$product_clean,$customer_clean,$quantity_clean)";
}
}
if ($query != ''){
if(mysqli_multi_query($db,$query)){
echo "Item Inserted"
}else{
echo "Error";
}
}else{
echo "No Product";
}
}
Hope someone can help me about this one. I'd put an alert in ajax to know if the it passes to the code. There's no insert happening even though it passes to the alert.

TypeError: document.getElementById(...).files is undefined

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

Delete record using jquery and ajax

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));

I am not getting response from ajax request

I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.

Categories