Fahad Almehaini Fahad Almehaini - 1 month ago 6
Ajax Question

Php mysql is returning only the last row when i use the auto refresh

I have the mysqli query which is returning only last record's value with all rows when i use the auto refresh with below code if i dont use the auto refresh then it works fine. Only problem I am facing when i use the auto refresh.

$(document).ready(function(){
refreshTable();
});

function refreshTable(){
$('.tableHolder').load('itemtotal_cart_checkout.php', function(){
setTimeout(refreshTable, 1000);
});
}


How can i fix that please help.

$ses_mem = $_SESSION['ses_user_id'];
$getItem = $_GET['item_id'];

$order_temp = "select * from temp_cart where item_id='".$getItem."' AND ses_mem='".$ses_mem."' order by id";
$tordera = $db->query($order_temp);
$torder = $tordera -> fetch_assoc();

Answer

Your PHP code expects item_id GET parameter. So you should pass it from JavaScript:

$('.tableHolder').load('itemtotal_cart_checkout.php?item_id=' + itemId,
  function(){
     setTimeout(refreshTable, 1000);
  });

Here's how you can get item_id from the current query string in JavaScript:

var m = location.search.match(/^.*[\?&]item_id\=(\d+)/);
var itemId = m && m.length >= 2 ? m[1] : 0;

If, however, the current page is a mixture of PHP and HTML with the JavaScript mentioned above, then just embed PHP into JavaScript:

<script>
/* skipped original code */
$('.tableHolder').load('itemtotal_cart_checkout.php?item_id=' + <?php
  echo isset($_GET['item_id']) ? (int) $_GET['item_id'] : 0;
?>,
  function(){
     setTimeout(refreshTable, 1000);
  });
/* skipped original code */
</script>

Finally, if the JavaScript is executed in a separate file, then you need a JavaScript function with an argument for item ID. For instance, in some script.js you might have a function similar to the following:

function refreshTable(itemId) {
    $('.tableHolder').load('itemtotal_cart_checkout.php?item_id=' + itemId, function() {
       setTimeout(function () { refreshTable(itemId) }, 1000);
    });
}

Then you can call it from PHP this way:

<script>
$(document).ready(function(){
  refreshTable(<?php echo isset($_GET['item_id']) ? (int) $_GET['item_id'] : 0; ?>);
});
</script>

You might want to use setInterval instead of recursive calls to setTimeout, by the way.

Comments