I am not getting response from ajax request - javascript

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.

Related

generate a post with an ajax and then send another ajax with post to another

I am trying to print on a thermal printer, this, after performing a query and obtaining certain data, which I send to a hidden input, the problem is that I do not know how to insert and use the second ajax post to my file php for printing, I am using the Mike42 ECPOS library. would you be so kind to guide me?
function calcCredits(){
/* variables from inputs */
var last_credit= parseInt(document.getElementById("studentcredits").value);
var namesec= document.getElementById("studentqr").value;
var credits= parseInt(document.getElementById("money").value);
var total_pay = credits * 35;
var ttl_credits = last_credit + credits;
/* Beggin Ajax */
$.ajax({
url:'addcredits.php',
type:'post',
data:{namesec:namesec,credits:credits},
success:function(data){
$.ajax({
url: 'ticket.php',
type: 'POST',
success: function(response){
alert('Printing....');
}
});
}
});
}
this is the php that performs the search and shows the results
<?php
require 'database.php';
$con = new Database();
$pdo = $con->conectar();
$campo = $_POST["campo"];
$sql = "SELECT * FROM students WHERE student_qr LIKE ? OR student_secondname LIKE ? ORDER BY student_secondname ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->execute([$campo . '%', $campo . '%']);
$html = "";
$data_query['result'] = $html;
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$html .= "
<div class=\"container-fluid \">
<div class=\"row\">
<div class=\"col-lg-12\">
<table class=\"table table-hover\">
<tr >
<th scope='col'>Grupo</th>
<th scope='col'>Nombre</th>
<th scope='col'>Créditos</th>
</tr>
<tr>
<td id='list_id'>".$row["student_group"]."</td>
<td id='list_id'>".$row["student_name"]." ".$row["student_secondname"]." ".$row["student_lastname"]."</td>
<td id='list_name'>".$row["student_credits"]."</td>
<td id='list_credits' style=\"cursor: pointer\" onclick=\"mostrar('" .$row["student_qr"] ."'), mostrar2('" .$row["student_credits"] ."')\"><button type='button' class='btn btn-warning' id= 'show' onclick='show()' >Añadir Creditos</button></td>
</tr>
</table>
</div>
</div>
</div>
";
}
echo json_encode($html, JSON_UNESCAPED_UNICODE);
and this is for printing
<?php
require __DIR__ . '/ticket/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
$nombre_impresora = "POS";
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->setJustification(Printer::JUSTIFY_LEFT);
$printer->text("Producto Galletas\n");
$printer->text( "2 pieza 10.00 20.00 \n");
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Muchas gracias por su compra\n");
$printer->feed(3);
$printer->close();
?>
sorry if it is not well structured I'm still practicing, thanks
After the comments and contributions that helped me a lot, I noticed that my mistake was to forward the info to another file, when the printing could be treated within the first insertion php, so I added the ticket code and that's it.
this is the ajax function
function calcCredits(){
$.ajax({
/* Se envian datos por POST a PHP */
url:'addcredits.php',
type:'post',
dataType: 'json',
data:{
studentqr:$('#studentqr').val(),
credits:$('#credits').val(),
},
})
.always(function(){
console.log("complete");
});
}
and then, the php insert
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("conection.php");
include("ticket/autoload.php");
$credits = mysqli_real_escape_string($con, $_POST['credits']);
$studentqr = mysqli_real_escape_string($con, $_POST['studentqr']);
$stmt = $con->prepare("UPDATE students
SET student_credits = (student_credits + ?)
WHERE student_qr = ?");
$stmt->bind_param("is", $_POST['credits'], $_POST['studentqr']);
$stmt->execute();
$insert_query = $con->prepare("INSERT INTO historical_credits (id_student, credits_paid)
SELECT id_student, ?
FROM students
WHERE student_qr = ?");
$insert_query->bind_param("is", $_POST['credits'], $_POST['studentqr']);
$insert_query->execute();
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
$nombre_impresora = "Termica";
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->setJustification(Printer::JUSTIFY_LEFT);
$printer->text("Producto Galletas\n");
$printer->text( "2 pieza 10.00 20.00 \n");
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Muchas gracias por su compra\n");
$printer->feed(3);
$printer->close();
$archivoActual = $_SERVER['PHP_SELF'];
header("refresh:2;url= + $archivoActual ");
mysqli_close($con);
?>
thanks a lot for your time

How to view data from DB with AJAX immediately after script counts it?

I am practising AJAX by implementing editable HTML table looking like this:
The logic is this:
User clicks on left column (containing integer);
JS script catches its value and by using AJAX adds them to database;
PHP script fetches this value, makes some calculations, adds them to database and shows result in right column (date in <td>).
Now as expected PHP script needs page refreshing to show calculation result (date in <td>). I'm trying to write JS script which will retrieve calculated data from database and immediately show in HTML table's cell.
Having troubles with it. Asking for help with this issue.
index.php:
<form id="form-wrap" action="functions.php" method="POST">
<select name="select1" required>
<?php
for ($i = 1; $i <= 20; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
<br>
<input type="text" id="name" name="name">
<input type="date" id="day" name="day">
<input type="submit" name="button_ok" id="button_ok" value="Write">
<input type="submit" name="show" id="show" value="Show table">
</form>
functions.php:
<?php
require_once 'dbconnect.php';
$loged = $_POST["name"];
$day = $_POST["day"];
class Count_Add_Class {
public function CountDays() {
global $day, $loged, $day_remind1, $days_before1;
$currenttime = time();
$days_before1 = $_POST["select1"];
// ... make some calculations with user's input ...
$this->AddDate();
}
public function AddDate() {
global $pdo, $loged, $day, $day_remind1, $days_before1;
if (isset($_POST['button_ok'])) {
// ... insert in database user's inpt and calculation result ...
}
}
}
$obj = new Count_Add_Class();
$obj -> CountDays();
function Count_days_new_data() {
global $pdo, $day, $loged, $day_remind1_updated,
$stmt = $pdo->prepare("SELECT select1 FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $row) {
$day_remind1_updated = $row['select1'];
}
$day_remind1_updated = $day - ($days_before1_updated * 86400);
$day_remind1_updated = date('Y-m-d', $day_remind1_updated);
}
Count_days_new_data();
function Show() {
global $pdo, $loged, $faq, $day_remind1_updated;
$stmt = $pdo->prepare("SELECT * FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$faq = $stmt->fetchAll();
$s1 = $_POST['editval'];
$id = $_POST['id'];
$stmt2 = $pdo->prepare("UPDATE tablex SET select1=? WHERE
id=?");
$stmt2->execute([$s1, $id]);
$stmt3 = $pdo -> prepare("UPDATE tablex SET day_remind1=?,WHERE
id=?");
$stmt3->execute([$day_remind1_updated, $id]);
require_once 'table.php';
}
Show();
?>
table.php:
<div id="day-data">
<tbody>
<?php
foreach($faq as $key=>$value) {
?>
<tr class="table_row">
<td><?php echo $value['name']; ?></td>
<td aria-label="First" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $faq[$key]["id"];
?>')" onClick="showEdit(this);"><?php echo $faq[$key]["select1"]; ?>
</td>
<td><?php echo $value['day_remind1']; ?></td>
</tr>
<?php
}
?>
edit.js:
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat
right");
$.ajax({
url: "functions.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
show.js: (inspired by this answer)
$(".tbl tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the
clicked tr
var value = $(this).find("td")[1].text()
$.ajax({
url : "table.php",
dataType: "text",
success : function (data) {
$(".day-data").html(data);
},
error: function (data) {
(".tbl").html('No such file found on server');
}
});
});
When user clicks on HTML-table left column it is higligted well; when he changes it, data is addiing to database well. Now when page is refreshed new data is calculated, added to database and shown in HTML-table's right column.
I suppose problem is in show.js. Need some help in correcting this script!
Update1:
Added illustartion of my task's logic:
It is unfortunate, that you have everything in the functions.php file. It doesn't just count the values, it also renders the table. So when you call the function saveToDatabase, the request that you make to functions.php (and i understand it coorectly) already returns the table with the updated data (as argument of the success function). Try removing show.js and changing the success function content in edit.js from this:
$(editableObj).css("background","#FDFDFD");
to this
$(editableObj).css("background","#FDFDFD");
$(".day-data").replaceWith(data);

Ajax request data could not show into the input field

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

want to update dropdown in each row in the database using Ajax

Here is my UI Screenshot. Highlighted is the Dropdown
What i want?
As i Select any option in the Dropdown it should get updated for that particular row in Database using AJAX
Below are the Codes that i've written. I'm just a Beginner, please excuse if the code is not neat!!
I'm using Codeigniter
Front End
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
Ajax Code - I've added a Console.log to see weather next row dropdown is being selected or not
$(document).ready( function() {
$(".statusClass").change(function(event) {
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $("select.statusClass").val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
*Console Ouputs for the first 3 rows show the 1 row selection thrice - Below is the Screeshots of that *
You are checking the values of all select box. Instead of that you get the values which you are updating to obtain the result this keyword will use.
$(document).ready( function() {
$(".statusClass").change(function(event) {
var status = $(this).val();

Getting callback results to send to AJAX from php and update table

I am updating a database table via AJAX and PHP right now, but I want my page to be more responsive and update my table in my file after the data has been inserted into the database table.
I am not sure how to send info from my php file to AJAX and then how to get AJAX to update the table. How can I call back the data from my PHP file in order to make my table interactive?
The table
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}
AJAX
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP file
$announcement_user_id= $_POST['user_id'];
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
I think to do this, the following steps is what you need:
Write a new php script that gets the items form the database (like in 'the table' script) and echo these items in the table format you want. So when you call this script, it echo's only a table containing the rows.
Remove the dynamic rows part from the 'the table' script.
On success of your ajax request, make a new request to the new php script
Place the output of that script in the html using jQuery (.html(), insertAfter(), appendTo(), or anything like that).
`

Categories