Reflect items from database using AJAX and JSON - php

I've been trying to use AJAX and JSON to show the contents of individual items from my database through the following codes below. What I'm trying to achieve is that whenever an individual item is opened or clicked, it will show up its unique content on the next page.
However, succeeding items just show the details of the initial item which has the ID '1'. I have more than 10 items in my DB and I want these to reflect their corresponding data.
//productpage_endpoint.php
require "connection.php";
$id = $_POST['id'];
$sql = "SELECT * FROM items WHERE id = $id";
$result = mysqli_query($conn,$sql);
$result = mysqli_fetch_assoc($result);
echo json_encode($result);
<script type="text/javascript">
$.post('productpage_endpoint.php',**{id: 1}**,
function(data){
var item = JSON.parse(data)
$('input[name=name]').val(item.name)
$('input[name=description]').val(item.description)
$('input[name=price]').val(item.price)
$('#item_image').attr('src',item.image)
}
)
</script>

If you'd like to request all items in the table:
$sql = "SELECT * FROM items";
In JS you'll need to create new elements for all of the values. Otherwise you'll overwrite the existing form values.
$.post('productpage_endpoint.php',
function(data){
for (var item in data) {
$('<input>')
.attr('name', 'name')
.attr('type', 'text')
.val(item.name);
// ...
// Add to your form...
}
}
)

Related

effect of updating data from multiple users sql php

I have a question please,
I am making an online store.
It offers a product with an available quantity attribute
Let's imagine a certain product has 1 quantity available only.
2 users are logged in and added this element to cart.
They both at the same time checked out (I am trying to do this by splitting 2 browsers in the screen and pressing at the checkout button simultaneously.)
How can I manage that the product checkout is successful for only one user in this case?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['qty_array'])&&isset($_POST['ids_array'])){
$order_address=$_POST['addressCart'];
$ids_array=$_POST['ids_array']; //this is array of product ids in the cart
$qty_array=$_POST['qty_array']; // this is array of quantities in the cart
$date=date("Y-m-d H:i:s");
$j=0;
$x=0;
foreach($ids_array as $id){
$query = "SELECT available_quantity from products where product_id='$id' AND product_active=1";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result);
$qty1=$qty_array[$j];
if($row['available_quantity']==0 || $qty1>$row['available_quantity']){
$x++;
}
$j++;
}
if($x!=0){
$msg="unable_checkout";
echo $msg;
}
else{
$bool=mysqli_query($db,"INSERT INTO order_table(customer_id,order_date,order_address)
VALUES ('$customerID','$date','$order_address')") or die("".mysqli_error($db));
$order_id=mysqli_insert_id($db);
if($bool){
$k=0;
foreach($ids_array as $id){
$query2 = "SELECT * from products where product_id='$id' AND product_active=1";
$result2 = mysqli_query($db,$query2);
$row2 = mysqli_fetch_array($result2);
$qty_available=$row2['available_quantity'];
$qty=$qty_array[$k];
$unitprice=$row2['product_price'];
$discount=$row2['product_discount'];
if($qty<=$qty_available && isset($_SESSION['cartProds']) && $qty_available!=0 ){
mysqli_query($db,"INSERT INTO order_details(order_id,product_id,unitprice,discount,quantity)
VALUES ('$order_id','$id','$unitprice','$discount','$qty')") or die("".mysqli_error($db));
$newqty=$qty_available-$qty;
mysqli_query($db,"UPDATE products SET available_quantity='$newqty' WHERE product_id='$id'");
}
$k++;
}
}
$msg="checkedout_successfully";
//unset inserted order :
unset($_SESSION['cartProds']);
$_SESSION['nOfProds']=0;
echo $msg;
}
}
I need to stop the submission and to not insert anything when one of the quantities is equal to Zero.
What I am getting is that if 2 users want to checkout 3 same products at the same time (one product is added to order table of user 1 , and the other 2 are added to order table of user2 ..which is wrong , I want in this case to make checkout successful for only one user, and to give a warning alert msg for the second user)
Ajax code:
$(document).ready(function() {
$("#enableAddress").change(function(){
if($("#enableAddress").prop("checked") == true){
$("#addressCart").prop('disabled',false);
}
else{
$("#addressCart").prop('disabled',true);
}
});
$("#checkoutBtn").click(function(){
var ids_array = [];
$('input[name^=checkoutHidden]').each(function(){
ids_array.push($(this).val());
});
var qty_array = [];
$('input[name^=quantity]').each(function(){
qty_array.push($(this).val());
});
var telCart = $("#telCart").val();
var addressCart = $("#addressCart").val();
$.ajax({
type: "POST",
url: "../phpOnly/checkOut.php",
data: { ids_array:ids_array, qty_array:qty_array,addressCart:addressCart},
success: function(msg) {
// alert(msg);
if(msg=="checkedout_successfully"){
// $("#orderMsg").fadeIn(3000);
// $("#cartBody").fadeOut(2000);
// $("#nOfProdsSpan").text('0');
alert(msg);
}
else if(msg=="unable_checkout"){
// window.location.href="#";
// $("#inavailableMsg").fadeIn(1000);
alert(msg);
}
}
});
});
});
Don't forget that I am taking into consideration that the available quantity is only 1 ( which only one user can order it only)
An approach to handle concurency would be to change the logic, and start the process by attempting to update the products table, with a where clause that ensures that the requested quantity is available, like so:
UPDATE products
SET available_quantity = available_quantity - 1
WHERE
product_id = :id
AND product_active = 1
AND available_quantity > 0
You can then check the number of rows affected by the query:
if one row was affected, then it means the that check out did succeed; you can then do the rest of the process (create the order and the order details records)
if no row was affected, then the check out failed; do not create the order
With this technique, you let the database handle the concurrency for you, and you are guaranteed to never sell more product than available.

Clear previous ajax response data before appending new data

I am trying to .append() a selected data from a radio button but it display all the previous respond result.
My HTML :
$sql = "SELECT DISTINCT(name) FROM table1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$i = 1;
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
$sql2 = "SELECT * FROM table1 WHERE list = '".$row['list']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<input name="group['.$i.']" class="id" type="radio" data-id="'.$row2['id'].'" />'.$row2['list'];
}
}
$sql2 = NULL;
$i++;
}
}
$sql = NULL;
My ajax to get data and append :
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
}
});
});
For PHP side if there is $_POST['id'] then do mysql query to filter from table and return result.
if(isset($_POST['id'])){
$sql = "SELECT * FROM table1 WHERE id = '".$_POST['id']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
}
}
}
So what happened in my ajax result box, it keep appending the previous data that been processed by ajax together with the new data.
EDIT : Example append result :
First result of selected radio button : string 1
Second result of selected radio button : string 2
So result should be :
string 1
string 2
Sorry there was a mistake with my explanation. My ajax box result is resulting something like this :
string 1
string 2 (new data from another selected radio)
string 2 (new data is duplicating)
If adding select another radio it will become like this :
string 1
string 2
string 2
string 3 (new data)
string 3 (new data duplicating)
string 3 (new data duplicating)
string 3 (new data duplicating)
My ajax box result :
<div id="list"></div>
Add any class in label and input
echo '<label class="ajax">'....
....
echo '<input class="ajax" ...
....
And Remove in each selection or change in ajax
$('.ajax').remove();
$('#list').append(data);
Or better
$('#list .ajax').remove();
$('#list').append(data);
Update
Or simple add div to your ajax response
$('#list').append("<div class='ajax'>"+data+"</div>");
and then use this code
$('#list .ajax').remove();
$('#list').append(data);
I think you jQuery looks ok. It would be possible for your SQL query to have multiple rows as a result. This could mean that your id value is actually returning two rows. They include the first row and the second row.
You should remove a previously-attached event handler from the elements to avoid multiple click.
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
$('.id').off('click'); // remove a previously-attached event handler from the element.
}
});
});

Ajax post request is not functioning

I don't understand why my ajax did not returning any value after post. I am displaying count of registered user in a html table and allowing admin to click each of the count to see list of user name.
My html displaying count of registered user :
$sql2 = "SELECT COUNT(*) AS count FROM reg WHERE reg_id = '".$row['reg_id']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<a class="slot" data-slotid='.$row['reg_id'].' href="">'.$row2['count'].'</a>';
}
}
$sql2 = NULL;
Ajax request :
$('.slot').on('click', function(){
var slotid = $(this).data('slotid');
$.ajax ({
type: 'POST',
url: 'my-domain.com/ajax-request',
data: { slotid : slotid },
success : function(htmlresponse) {
$('#user_list').html(htmlresponse);
console.log(htmlresponse);
}
});
});
My php function from another file to filter database row :
if(isset($_POST['slotid'])){
// Mysql SELECT statement and echo query result
}
If I place a alert(slotid) right after var slotid = $(this).data('slotid'); in the ajax function, it will display the correct value for each of the clicked link. But when I try to echo $_POST['slotid']; at php side, there is not value returned. It seems like the whole page is refreshing.

Auto Refresh DIV contents from Mysql table - one at a time

I need to automatically refresh content from a mysql data table every 5 seconds, but showing only one distinct record at a time, going through every record in a endless loop.
I load news.php, that has this js :
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#canvas').load('content.php').fadein("medium");}, 5000);
// refresh every 5 seconds
</script>
content.php has the db connection
$query_Recordset5 = "SELECT * FROM news";
$Recordset5 = mysql_query($query_Recordset5, $connection) or die(mysql_error());
$row_Recordset5 = mysql_fetch_assoc($Recordset5);
$totalRows_Recordset5 = mysql_num_rows($Recordset5);
As well as the fields echoed to the page.
I understand that you would have to create a counter and bring back one different record everytime, but I am having a tough time with it.
Thanks
If your table has an auto increment field (say "id"). You start by passing page.php and id of 0, so it will grab the auto increment field greater than 0, and then you pass that fields ID back through jquery. When you send it a second time it will not be included because you will be using the greater than sign.
The if num_rows == 0 checks to see if there are any fields, if none, then it will assume that the auto increment field you sent it is the last one, and then it will run the sql statement with the very first auto increment value.
<?php
// page.php
$id = (int) $_REQUEST['id'];
$sq = "select * from news where id > ".$id." order by id asc limit 0,1";
$qu = $con->query($sq);
if ($qu->num_rows == 0) {
$sq2 = "select * from news order by id asc limit 0,1";
$qu2 = $con->query($s2);
while ($fe = $qu->fetch_assoc()) {
echo $fe['id']."|".$fe['content'];
}
} else {
while ($fe = $qu->fetch_assoc()) {
echo $fe['id']."|".$fe['content'];
}
}
?>
<script>
$(document).ready(function() {
setInterval(function(){ updateNews(); }, 5000);
});
function updateNews() {
var id = 0;
id = $("#hidden-id").val();
$.get("page.php?id=" + id, function(data) {
// I use $.get so that I can split the data that it returns before populating
// the #canvas. This way we can strip off the first part which is the auto
// increment
var ref = data.split('|');
$("#hidden-id").val(ref[0]);
$("#canvas").html(ref[1]);
});
}
</script>

Ajax Printing Database Records to Multiple Fields

I currently have code which will pull the first element from a database record and print it in an output box.
What is the easiest way to print the rest of the elements of that record to the other relevant output boxes?
My PHP file takes an 'id' specified by the user.
$id = $_POST['id'];
$query = "SELECT * FROM Customers WHERE ID = $id";
$result= mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo $row[1];
}
}
And this is the code in the HTML file
jQuery(document).ready(function(){
jQuery("input.myid").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
var search_val=jQuery("input.myid").val();
jQuery.post("find.php", {id : search_val}, function(data){
if (data.length>0){
jQuery("input.fname").val(data);
}
});
}
The code takes the id ('myid') and prints to a text box named 'fname'.
I find it easier to json_encode the whole thing (record I mean) and use something like jquery.populate which basically takes an object and fills a form with it (all fields it can find which names' match properties from the object).
I hope this makes sense.

Categories