query to fetch tables after a certain timestamp not working - php

I am trying to calculate the total earnings after a certain timestamp.
What I want to do:
I have a button which on click adds the total earnings till that time to the table with a timestamp.
As soon as it gets added to the database, from there on i want to display the total earnings earned after that timestamp.
So, that means if there are no earnings after the click of the button, it should show me 0.
Problems:
The thing works only the first time if the database is empty. Otherwise Values are correctly inserted in the database but the jquery doesnt update the span tags each time I hit the button.
HTML:
<span id="wb_uid8">Earned: </span><span id="wb_uid9">Fetching data..</span>
<input type="submit" id="Button1" name="Button1" value="I received my incentive today!">
<span id="wb_uid10"><strong>Last payment receive date:</strong></span><span id="wb_uid11"> </span><span id="wb_uid12"></span><span id="wb_uid13"><br>
</span><span id="wb_uid14"><strong>Received amount:</strong></span><span id="wb_uid15"> </span><span id="wb_uid16"></span>
jQuery:
<script>
$(document).ready(function()
{
$('#Button1').click(function(){
var fullDate = new Date();
var twoDigitMonth = fullDate.getMonth()+"";
if(twoDigitMonth.length==1){
twoDigitMonth="0" +twoDigitMonth;
}
var twoDigitDate = fullDate.getDate()+"";
if(twoDigitDate.length==1){
twoDigitDate="0" +twoDigitDate;
}
var currentdate = twoDigitDate+"/"+twoDigitMonth+"/"+fullDate.getFullYear();
var dataString = 'date='+currentdate;
$.ajax({
type:"POST",
data: dataString,
url: "receipts.php",
cache:false
});
return false;
});
});
</script>
<script type="text/javascript">
$(function(){
setInterval(function(){
$.ajax({
url: 'checkearnings.php',
success: function(data){
var data=JSON.parse(data);
$('#wb_uid9').html('₹ '+ data['earned']);
$('#wb_uid12').text(data['lastdate']);
$('#wb_uid16').html('₹ '+ data['lastamt']);
}
});
}, 1000);
});
</script>
checkearnings.php
<?php
include 'connect.php';
$earned = 0;
$lastdate = "";
$lastamt = "";
$timestamp = "";
$sql = "SELECT * FROM receipts ORDER BY date DESC LIMIT 1";
$result1 = mysqli_query($db, $sql);
if($details = mysqli_fetch_array($result1)){
$lastdate = $details['date'];
$lastamt = $details['amt'];
$timestamp = $details['timestamp'];
}
else{
$lastdate = "Never";
$lastamt = "Nothing";
}
$sql = "SELECT amt FROM sales WHERE timestamp>'$timestamp'";
$result = mysqli_query($db, $sql);
while($fetch_options=mysqli_fetch_array($result)){
$earned = $earned + $fetch_options['amt'];
}
$responses=array('earned'=>$earned, 'lastdate'=>$lastdate, 'lastamt'=>$lastamt);
$return=$responses;
//echo $earned;
echo json_encode($return);
?>
receipts.php
<?php
include 'connect.php';
include 'checkearnings.php';
if (isset($_POST['date']))
{
$newdate = $_POST['date'];
$time = round(microtime(true)*1000);
$sql = "INSERT `receipts` (`date`, `amt`, `timestamp`) VALUES ('$newdate', '$earned', '$time')";
$results = mysqli_query($db, $sql);
mysqli_close($db);
}
?>

Related

Jquery, Ajax save to database

I am trying to create a simple attendance register for a kids club, when they turn up for a practice session they need to record who's paid on the night. It's more or less works as I want it to, but I'm struggling with the last bit.
When I click on the button to add a user_id to the paid table, along with the date and and status, it does as expected, so all good there. However, I would like the button to change icons based on Paid status, which I can do buy reading a database value -
<button type="button" class="btn btn-sm btn-success btn-status" id="<?php echo $row['user_id']; ?>" data-status="<?php echo $row['status']; ?>" title="Active/Deactive details" >
<?php if(empty($row['status'])){ ?>
<i class="fa fa-thumbs-up" aria-hidden="true"></i>
<?php }else{ ?>
<i class="fa fa-ban" aria-hidden="true"></i>
<?php } ?>
On button click the following jQuery handles the post event -
$(document).on('click', '.btn-status', function(ev){
ev.preventDefault();
var btn_button = $(this);
var status = 1;
btn_button.html(' <i class="fa fa fa-spinner fa-spin"></i> ');
var tbl_id = $(this).attr("id");
var tbl_status = $(this).data("status");
if(tbl_status == 0) status = 1;
else status = 0;
$.post('save_details.php', { form_name: "user_status", tbl_id: tbl_id, status: status }, function(data,status){
console.log(data);
if(data == "1"){
$('.warning-modal-message').html("Record status changed successfully.");
$('#warningModal').modal('show');
setTimeout(function(){ location.reload(); }, 2000);
}
else{
$('.warning-modal-message').html("Data deletion failed.");
}
});
});
And the PHP for the database -
if($form_name == "user_status"){
$tbl_id = mysql_real_escape_string($_POST['tbl_id']);
$status = mysql_real_escape_string($_POST['status']);
$query = "insert into attendance(rider_id, at_status, at_date) values('$tbl_id','$status',NOW())";
$result = mysql_query($query) or die(mysql_error());
if($result)
echo "1";
else
echo "0";
}
The problem I'm having is the the query relies on the status field in the user data table to control which icon is visible. What I need is a way to have all the icons set to fa-ban icon on page reload and the thumb icon when the button is pressed to take attendance.
I have tries setting the $row['status']; to 1 manually, I have tried Bootstrap Toggle Switch, Bootstrap Toggle Button and loads of articles on here but I'm not having any luck
I managed to get it working more or less as needed using Bootstrap Toggle Switch -
<input type="checkbox" id="<?php echo $row['user_id']; ?>" class="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Paid Fees" data-off="Unpaid" data-onstyle="success" data-offstyle="danger" data-size="small" >
Using the following jQuery -
$(document).on('change', '.toggleBtn', function(ev){
ev.preventDefault();
// Disable switch on click to help prevent multiple submit
$(this).bootstrapToggle('disable');
//var btn_button = $(this);
var status = $(this).prop('checked');
//btn_button.html(' <i class="fa fa fa-spinner fa-spin"></i> ');
var tbl_id = $(this).attr("id");
var tbl_status = $(this).data("status");
//if(tbl_status == 0) status = 1;
//else status = 0;
$.post('save_details.php', { form_name: "user_status", tbl_id: tbl_id, status: status }, function(data,status){
console.log(data);
if(status == "checked"){
$('.warning-modal-message').html("Record status changed successfully.");
$('#warningModal').modal('show');
setTimeout(function(){ location.reload(); }, 2000);
}
else{
$('.warning-modal-message').html("Data deletion failed.");
}
});
});
And the following PHP -
if($form_name == "user_status"){
$tbl_id = mysql_real_escape_string($_POST['tbl_id']);
$status = mysql_real_escape_string($_POST['status']);
//SELECT * FROM `attendance` WHERE `rider_id` = 1 AND `at_date` = DATE(NOW())
$result = "SELECT * FROM `attendance` WHERE `rider_id` = '$tbl_id' AND `at_date` = DATE(NOW())";
$total = ($result);
if($total==0){
$query = "insert into attendance(rider_id, at_status, at_date) values('$tbl_id','$status',NOW())";
$result = mysql_query($query) or die(mysql_error());
}
//$query = "insert into attendance(rider_id, at_status, at_date) values('$tbl_id','$status',NOW())";
//$result = mysql_query($query) or die(mysql_error());
//if($result)
//echo "1";
//else
//echo "0";
}
A couple of the issues I'm having now is that the warnings are not showing up and the $qry to check if a rider has already been entered on the day (the switches are reset on page refresh!
if(status == "checked"){
$('.warning-modal-message').html("Record status changed successfully.");
$('#warningModal').modal('show');
setTimeout(function(){ location.reload(); }, 2000);
}
else{
$('.warning-modal-message').html("Data deletion failed.");
}
Thanks!

AJAX SET INTERVAL

I want to get the latest post_id in the table without refreshing it, but the problem is whenever a user inserts a value to the database, It echoes infinitely the last post_id. I want it to echo only once. But I still want to get the latest post_id from the table.
Here is my main php:
<div id = "this_div">
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
$execute_query = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($execute_query))
{
$get_this_id = $row['post_id'];
echo $get_this_id."<br>";
}
$_SESSION['get_this_id'] = $get_this_id;
?>
</div>
here is my jQuery ajax:
<script>
var refreshId = setInterval(function(){
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
$.ajax({
url: 'another_file.php',
data: {},
success: function(data)
{
if(compare_session != data)
{
$('#this_div').text($('#this_div').text()+data);
}
}
});
},400);
</script>
here is the php code of another_file.php
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
$execute_query = mysqli_query($con,$query);
if($row = mysqli_fetch_assoc($execute_query))
{
echo $get_this_id = $row['post_id'];
}
?>
You are not updating the compare_session variable , it holds always the initial value . So update it inside success callback function
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: {},
success: function (data) {
if (compare_session != data) {
$('#this_div').text($('#this_div').text() + data);
}
compare_session = data;
}
});
}, 400);

how to update number without reloading

I am working on a voting system in jquery. I have it where a user can vote up or if they change their mind vote down and it deducts from the upvote and puts it in on the down vote. But my problem is I cant get both numbers to refresh when a vote is selected so it just uses the original number instead of the updated number.
Vote Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
</script>
<?php
$sql=mysql_query("SELECT * FROM uploads LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['title'];
$mes_id=$row['id'];
$up=$row['up'];
$down=$row['down'];
?>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?> up
</a>
<div class='down'>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?>
</a>
</div>
<div class='box2' >
<?php echo $msg; ?>
</div>undefined</div>undefined
<?php } ?>
The up_vote.php page..
(down_vote.php is exactly the same as up_vote except it just changes up to down.)
<?php
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
if ($_POST['id']) {
$id = $_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql = mysql_query("select ip from votes where img_id='$id' and ip='$ip'");
$count = mysql_num_rows($ip_sql);
if ($count == 0) {
// Update Vote.
$sql = "UPDATE uploads SET up=up+1 WHERE id='$id'";
mysql_query($sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into votes (id,img_id,ip,type) values ('','$id','$ip','up')";
mysql_query($sql_in);
} else {
//if already voted change it..
$result = mysql_query("SELECT * FROM votes WHERE img_id='$id' AND ip='$ip'");
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
$up = mysql_query("UPDATE uploads SET up=up+1 WHERE id='$id'");
$down = mysql_query("UPDATE uploads SET down=down-1 WHERE id='$id'");
$vote = mysql_query("UPDATE votes SET type=up WHERE img_id='$id' AND ip='$ip'");
}
}
$result = mysql_query("select up from uploads where id='$id'");
$row = mysql_fetch_array($result);
$up_value = $row['up'];
echo $up_value;
}
?>
Not an answer but too long for a comment. This script:
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
/* ... */
}
I don't think you need it like it is now. You are actually only using the last fetched row, not all of them. If that's your intention (because there's only one), then you don't need the while() at all. You could change it for:
$row = mysql_fetch_row($result);
$vote_type = $row['type'];
if ($vote_type == 'down') {
/* ... */
}
Furthermore, I'd recommend to change your code to PDO. It's more secure and mysql_* is deprecated.

Issues with long polling and sessions (chat)

I made a friends chat that uses textfiles to store data and it all works more or less except when I sign in and write something to someone, nothing pops up (but the text is stored in the appropriate text file), then when I refresh the page it is ok from THEN ON, but on the other browser as the other user I have to also refresh the page in order for it to work normally both ways.
Basically, every time I log in I have to click the name of the person I want to chat with, then a window pops out and THEN i have to refresh or else it doen\sn't work.
I guess I have to kind of refresh the page whenever I click on a friend and want to chat with him and that it is a session problem.
here is home.php (users are redirected here when they log in on index.php page)
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">#import 'custom_chat.css';</style>
</head>
<body>
<h2>Hello, <?php echo $_SESSION['user']; ?></h2>
<hr>
<p><b>CONTACTS:</b></p>
<?php
require_once 'dbc.php';
$u = $_SESSION['user'];
$q = "SELECT user_id FROM users WHERE username='$u'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
// current user id
$uid = $row[0];
$q = "SELECT u.username FROM users AS u, friends AS f
WHERE (f.f1 = '$uid' OR f.f2 = '$uid') AND (f.f1 = u.user_id OR f.f2 = u.user_id) AND (u.username != '$u')";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r)) {
echo '<div class=chat_contacts>';
echo '<div class='.$row['username'].'>';
echo '<div class=inner>';
echo '<div class=inner_chat></div>';
echo '<form>
<textarea class=chat_text></textarea>
</form>
';
echo '</div>'; // end .inner
echo '<a href="#" class='. $row['username'] .'>'.$row['username'] .'</a>
</div>';
echo '</div>'; // end .chat_contacts
}
?>
<p>HOME</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
var nc = '<?php echo $u ?>';
// toggle chat window
$('.chat_contacts a').click(function() {
$(this).prev('div.inner').toggle();
var tc = $(this).attr('class');
$(this).parent().parent().addClass(nc+tc);
$('textarea').focus(); // MD maybe
return false;
});
// call main chat function
$(function () {
updateChat();
}); // end ready
//update on enter
$('textarea.chat_text').keypress(function(e) {
$this = $(this); // textarea
if (e.which == '13') {
insertChat();
return false;
}
});
function insertChat() {
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
alert(data)
}
});
}
var timestamp = 0;
function updateChat() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
// if (json['msg'] != null) {
$('.chat_contacts.'+nc+json['nru']+' .inner_chat').append('<p>'+json['msg']+'</p>'); // MD
// }
timestamp = json['timestamp'];
setTimeout('updateChat()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('updateChat()', 1000);
}
});
}
</script>
</body>
</html>
update.php
<?php
session_start();
require_once('dbc.php');
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
$ou = $_SESSION['user'];
$ru = $_SESSION['ru'];
session_write_close();
$q = "SELECT * FROM chats WHERE
(chats.f1='$ru' AND chats.f2='$ou') OR (chats.f1='$ou' AND chats.f2='$ru') ORDER BY time DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
// $filename = 'vojaolja.txt';
$q = "SELECT user_id FROM users WHERE username='$ou'
ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$fu = $row[0];
$q = "SELECT user_id FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$su = $row[0];
$q = "SELECT username FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$nru = $row[0];
if ($fu < $su) {
$filename = $fu.$su.'.txt';
} else {
$filename = $su.$fu.'.txt';
}
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$data = file($filename);
$line = $data[count($data)-1];
$response['msg'] = $line;
$response['nru'] = $nru;
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Also, if someone wants to reproduce this on their own computer, I can post all the code here, it is just a few pages, it can be setup together with the database in literally 2 minutes.
EDIT:
as soon as I login, i see the following in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509358392 (plus the rolling thingy, it is waiting)
Then i click on a friend's name, window pops up, I write something and i get this in the console:
http://localhost/x_super_chat/insert.php
AND THEN WHEN I REFRESH AGAIN (when it actually starts working) I get the following in the console.
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509491493
http://localhost/x_super_chat/update.php?timestamp=1374509435&_=1374509493231 + the waiting thingy icon, it is waiting
So it changes after refresh, I need what I get after refresh to be there as soon as I log in.
EDIT 2: (after Pitchinnate's answer)
As soon as I login, I see this in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185 (plus the waiting animation)
Then I write something to the other person (say John), and I get the following:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566817682
http://localhost/x_super_chat/update.php?timestamp=1374565160&_=1374566817740
http://localhost/x_super_chat/update.php?timestamp=1374566817&_=1374566817801 (plus waiting animation)
THEN when I write something on the other side as John, I get the following: (this is from chrome so it is not the same as the console in firebug):
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566987051
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=1374566995&_=1374567004175
http://localhost/x_super_chat/update.php?timestamp=1374567004&_=1374567004215
One thing you can try is cancelling your long poll upon insert, create a global javascript variable outside your update function var myajax;
myajax = $.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
Then on insert:
function insertChat() {
myajax.abort();
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
updateChat();
}
});
}

ajax is not able to retrieve the parsed array by the PHP

I have a table sets in a popup window to show orders placed by a specific userID
<div id="shpcart">
<div id="shpop">
<table>
<thead>
<tr><th></th><th>Item name</th><th colspan="2">Price</th><th>shipping</th></tr><th>Quantity</th>
</thead>
<tbody id= "cartbody">
</tbody>
</table>
</div>
</div>
Here is the ajax to send the userID to the server
$(function(){
$(".prod_buy").click(function(){
var htmlId = $(this).attr('id');
var idarray = htmlId.split('-');
var itemId = idarray[1];
$.ajax({
type: "POST",
url: "tempselector.php",
data: {'proId': itemId }
}).done(function( msg ) {
jQuery.parseJSON(msg);
var output = jQuery.parseJSON(msg);
var htmlstring;
alert ("im running");
for(var index=0;index<output.length; index++){
var itmnam = output[index][1];
var itmpic = output[index][2];
var itmpr = output[index][3];
var itmdisc = output[index][4];
var itmdesc = output[index][5];
var itmshp = output[index][6];
var itmav = output[index][7];
htmlstring +="<tr><th><img src = '../cartimg/'"+itmpic+"></th><td>"+itmnam+"</td><td>"+itmdisc+"</td><td>"+itmshp+"</td><td>QTY</td></tr>";
}
$('#cartbody').html(htmlstring);
$("#shpcart").fadeIn();
});
});
and here is the PHP to fetch the order of the passed user id
<?php
session_start();
include('includes/config.php');
$uId = $_SESSION["uId"];
$prID = mysqli_real_escape_string($link,$_POST["proId"]);
//$pQty = mysqli_real_escape_string($link,$_POST["prQTY"]);
$pQty = 2;
//$prID = 4;
$sqlget= "SELECT * FROM vasplus_programming_blog_pagination WHERE id='".$prID."'"; // to find the selected item
$resultget = mysqli_query($link, $sqlget);
$itemget = mysqli_fetch_array($resultget);
$itemId = $itemget[0]; // store the selected id in var
$itemNm = $itemget[1];
$ITimage = $itemget[2];
$ITprice = $itemget[3];
//$ITdiscount =$itemget[4];
$ITdescription =$itemget[5];
$ITshipping =$itemget[6];
// $ITavailable = $itemget[7];
$ITcontrycod =$itemget[8];
$itemCol = $itemget[9]; // store the selected color in var
$itemSiz = $itemget[10]; // store the selected size in var
$ITqty = $itemget[11];
// we need to search the temp table to see if the selected item is there
$sqlsrch= "SELECT * FROM XXXXX WHERE product_id ='".$prID."' AND size = '".$itemSiz."' AND color = '".$itemCol."' AND user_id = '".$uId."' "; // if the item is in the temp table or not
$resultsrch = mysqli_query($link, $sqlsrch);
$itemsrch = mysqli_fetch_array($resultsrch);
echo $itemsrch;
if (isset($itemsrch)){
$adqty = $itemsrch[8];
$adqty ++;
$sqlupdate=" UPDATE XXXXXX SET qty='".$adqty."' WHERE product_id ='".$prID."' AND size = '".$itemSiz."' AND color = '".$itemCol."' AND user_id = '".$uId."' "; // update the qty of theexisting items in temp table
$resultupdate = mysqli_query($link, $sqlupdate);
}else {
echo " user id searching ";
$sqlisUsr= "SELECT * FROM XXXXXX WHERE user_id = '".$uId."' "; // check if the user has any item in the temp table
$resultisUsr = mysqli_query($link, $sqlisUsr);
$isUsr = mysqli_fetch_array($resultisUsr);
if (isset($isUsr)){ // if user has items in the cart
$getOrdId = $isUsr[2]; // get the order ID
$sqladdN=" INSERT INTO XXXXXXx (order_id, user_id, photo, express, qty, unit_price, country, color, size, product_id) VALUES ('$getOrdId', '$uId' , '$ITimage' , '$ITshipping' , '$pQty', '$ITprice' , '$ITcontrycod' , '$itemCol' , '$itemSiz' , '$prID' ) "; // insert the item with the existing order ID
$resultaddN = mysqli_query($link, $sqladdN); }else{ // user has no record in temp order
echo " else is running " ;
$ReNth = 0;
$oId = 1;
while ($ReNth != 1){
$sqlNewOiD= "SELECT * FROM XXXXXX WHERE order_id = '".$oId."'"; // generate a new order ID
$resultOsrch = mysqli_query($link, $sqlNewOiD);
$oIdsrch = mysqli_fetch_array($resultOsrch);
if (isset($oIdsrch)){
echo $oId++;
echo " order Id generated " .$oId;
}else{ // insert the new item with the new order id in the temp table
echo $oId."oId<br />" ;
echo $uId."uId<br />" ;
echo $ITimage."<br />" ;
echo $ITshipping."<br />" ;
echo $pQty."<br />" ;
echo $ITprice."<br />" ;
echo $ITcontrycod."<br />" ;
echo $itemCol."<br />" ;
echo $itemSiz."<br />" ;
echo $prID."<br />" ;
$sqladdNOID = " INSERT INTO XXXXXx (order_id, user_id, photo, express, qty, unit_price, country, color, size, product_id) VALUES ('$oId', '$uId' , '$ITimage' , '$ITshipping' , '$pQty', '$ITprice' , '$ITcontrycod' , '$itemCol' , '$itemSiz' , '$prID' ) ";
$resultaddNOID = mysqli_query($link, $sqladdNOID);
$ReNth = 1; // quit the searching for unique order id loop
}//end if
}//end while
}// end if
}// end if
// pars json code for the cart
$sql= "SELECT * FROM XXXXX WHERE user_id = '".$uId."'" ;
$result = mysqli_query($link, $sql);
while($item = mysqli_fetch_array($result)){
$array[] = $item;
}
echo json_encode($array);
?>
The problem is that the ajax is not able to retrieve the parsed array by the PHP. I see that the $uId being passed to the PHP and the PHP code works fine and $array has been fetched, but in return the ajax isn't able to read the $array .
please help me here
about the ajax method, you can try this code:
$.ajax({
url:'tempselector.php',
dataType:"json",
type:"GET",
data: {'proId': itemId },
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('body').append(XMLHttpRequest.responseText);
},
success:function(output){
var htmlstring;
for(var index=0;index<output.length; index++){
var itmnam = output[index][1];
var itmpic = output[index][2];
var itmpr = output[index][3];
var itmdisc = output[index][4];
var itmdesc = output[index][5];
var itmshp = output[index][6];
var itmav = output[index][7];
htmlstring +="<tr><th><img src = '../cartimg/'"+itmpic+"></th><td>"+itmnam+"</td><td>"+itmdisc+"</td><td>"+itmshp+"</td><td>QTY</td></tr>";
}
$('#cartbody').html(htmlstring);
$("#shpcart").fadeIn();
}
});
if unnecesary output is present then json can not be parsed, that's the issue. problem has been solved

Categories