Best Way to update PHP Variable? - php

I am currently having some issues with updating a PHP variable without refreshing the page.
In my situation the code will count the products and if there are none it won't shoot anything out. If the quantity of $total is 1 or greater it will display the amount.
<?php
$total = count_products();
if ($total == 0) {
echo " ";
} else {
echo $total;
}
?>
Now what I am having trouble with is how to update that variable. If I were to add a product, I would not see the updated result until refreshing the page completely. Is there a nice way to update the $total without having to refresh the page?

You can try ajax to do that for you without refreshing page
Basic example here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".thebutton", function(e) {
e.preventDefault();
$("#result").load(location.href+ ' #my');
});
</script>
<button href="#" class="thebutton"> add product button</button>
<div id="result">
<div id="my">
<?php
//echo time for demonstration
echo date('a:i:s');
?>
<!-- lets say this is where you echo your total -->
<?php
$total = count_products();
if ($total == 0) {
echo " ";
} else {
echo $total;
}
?>
</div>
</div>
Hope this would be of some help to you

Related

Looping jquery function load() using php mysql doesn't work it loop first row only

I need to show the posts count depend on topic id using auto load jquery load() after looping the result using php but unfortunately it shows the first row and uses that first row to show another count and change again
Any Help please!
index.php
<?php
foreach($t_all_rows as $row){
?>
<tr>
<td class="text-center hidden-xs hidden-sm">
<a class="font-w600" href="javascript:void(0)">
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_posts').load('get_posts.php?t_id=<?php echo $row['t_id']; ?>').fadeIn("slow");
}, 1000); // refresh every 5000 milliseconds
</script>
<span id="load_posts"></span>
</a>
</td>
</tr>
<?php } ?>
get_posts.php
include('connection.php');
$db=new DB();
$conn=$db->db_connect();
$my_t_id=$_GET['t_id'];
$post_query = mysqli_query($conn,'SELECT * FROM post WHERE t_id = "'.$my_t_id.'"');
$record_count=mysqli_num_rows($post_query);
//Display count.........
echo $record_count;
that is normal, because get only first div by ID, change the span id or add a new class with loop number
Adding $k
foreach($t_all_rows as $k => $row){
Adding new class
<span id="load_posts" class="load_post<?=$k?>"></span>
change jquery code:
$('.load_post<?=$k?>').load
But importan, I am suggest to you, to upgrate the mysql query using JOIN and not use jquery
Thanks for the help i finally realize i shoud use class instead of id
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('.load_posts<?php echo $index; ?>').load('get_posts.php?t_id=<?php echo $row['t_id']; ?>').fadeIn("slow");
}, 1000); // refresh every 5000 milliseconds
</script>
<span class="load_posts<?php echo $index; ?>"></span>

Reconciling Show/Hide JQuery Script into PHP

I currently have some php script that outputs results from a query. I would like to add at the end two buttons that will show/hide the final element, but am not sure how to do this.
The following is my php script:
while($result = mysqli_fetch_array($iname))
{
echo "<b>Event Name:</b> " .$result['EventName'];
echo "<br> ";
echo "<b>Location:</b> ".$result['Location'];
echo "<br>";
//this is where I would like to add my two buttons, that would show the "hidden" content when clicked
And here is what I have written in an HTML script, that I would like to reconcile into the PHP output:
<!DOCTYPE html>
<html>
<head>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js></script>
<script>
$(document).ready(function(){
$("#hidden").hide();
$("#hide").click(function(){
$("#hidden").hide(500);
});
$("#show").click(function(){
$("#hidden").show(500);
});
});
</script>
</head>
<body>
<button id="show">Show</button>
<button id="hide">Hide</button>
<p id="hidden">
Some Random Text that will be shown when the buttons are clicked
</p>
</body>
</html>
Any suggestions as to how this should be done?
How about if you get the number of result rows with $num_rows = mysql_num_rows($result);
Then, put a counter in your loop.
$counter = 1;
$theClass="";
while($result = mysqli_fetch_array($iname))
{
if ($counter == mysql_num_rows($result);){
$theClass="showHide";
}
echo "<div class='$theClass'>";
echo "<b>Event Name:</b> " .$result['EventName'];
echo "<br> ";
echo "<b>Location:</b> ".$result['Location'];
echo "<br>";
echo "</div>
$counter++;
}
Then, apply your javascript to the div whose class="showHide"

How to get Infinite Ajax Scroll working with filtering and ordering. PHP / JQUERY

My goal is to have a responsive page containing a list of divs which users can browse. I need to use server side pagination using infinite scrolling. I also want to be able to apply filters and ordering to the list. I have spent while looking for different solutions and come across (http://isotope.metafizzy.co/) which looks perfect for what I want, however, in the documentation it advises against using filtering and infinite scrolling together.
Instead I have implemented the infinite-ajax-scroll (https://github.com/webcreate/infinite-ajax-scroll) plugin onto my project and decided not to filer and order using ajax as not to over complicate it (and due to limited ajax / jquery knowledge). However this does not work, what happens is the page loads with the correct filters but then when the 2nd page loads, the filter is no longer applied. How do I pass the filter $cat so that it scrolls?
Below is what I have thus far.
$cat = (isset($_GET['cat']) ? urldecode($_GET['cat']) : '');
$page = (int) (!isset($_GET['p'])) ? 1 : $_GET['p'];
$start = ($page * $pagelimit) - $pagelimit;
$limit = $pagelimit*$page;
//get total number of discounts for search
$total_items = Stuff::countItems($cat);
if( $total_items > ($page * $limit) ){
$next = ++$page;
}
//get items
$items = Stuff::getItems($cat, $sortby, $dir, $start, $limit);
if(!$items){
header('HTTP/1.0 404 Not Found');
echo 'Page not found!';
exit();
}
?>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ias.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Infinite Ajax Scroll configuration
jQuery.ias({
container : '.wrap', // main container where data goes to append
item: '.item', // single items
pagination: '.paginate', // page navigation
next: '.paginate a', // next page selector
loader: '<img src="css/ajax-loader.gif"/>', // loading gif
noneleft: 'No more items', //Contains the message to be displayed when there are no more pages left to load
triggerPageThreshold: 5, // show "load more" if scroll more than this to stop
trigger: "Load more items"
});
});
</script>
</head>
<body>
<div class="wrap">
<?php
echo 'TOTAL: '.$total_items .'<br />';
//filter through categories*/
echo 'FILTER BY CATEGORY:';
foreach ($categories as $category){
$categoryURL = urlencode($category);
echo "<a href=\"index.php?cat=$categoryURL\">$category<a/> | ";
}
//loop through and display items
foreach ($items as $id => $item){
echo "<div style=\"border:1px solid green;margin-bottom:5px;\" class=\"item\" id=\"item-$id\">
ID: $id <br />
$item[name]<br />
$item[cat]<br />
$item[description]<br />
</div>";
}
?>
<!--paginagation-->
<?php if (isset($next)): ?>
<div class="paginate">
<a href='index.php?cat=<?php echo $cat?>&p=<?php echo $next?>'>Next</a>
</div>
<?php endif?>
</div>
</body>
</html>
Have you tried:
<div class="paginate">
<a href='index.php?cat=<?php echo urlencode($cat); ?>&p=<?php echo $next?>'>Next</a>
</div>

pass jquery variable to php page and receive calculated variable to first page

I have a generated table which i need when press button on 6th column to get 1st cell value in the row and send it to an overlay page, the overlay page will do some calculations which will take some time and show a score, i want to replace the 6th column button with that score.
I cant get page2.php to show in the over lay while processing (i use popup from here)
here is what i reached so far
<tbody>
<?php foreach ($rows as $row_number => $columns): ?>
<?php
$row_class = 'row-' . ($row_number + 1);
if ($row_number == 0) {
$row_class .= ' row-first';
}
if (count($rows) == ($row_number + 1)) {
$row_class .= ' row-last';
}
?>
<tr class="<?php print $row_class; ?>">
<?php foreach ($columns as $column_number => $item): ?>
<td class="<?php print 'col-'. ($column_number + 1); ?>" >
<?php print $item; ?>
</td>
<?php endforeach; ?>
<td>
<?php print $dnsearch; ?>
</td>
<td>
<button id="my-button">Get Score</button>
<div id="element_to_pop_up">
<a class="bClose">x<a/>
here should page2.php receive the variable from script and do the processing and return data (score) to replace the clicked button
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">
$(":button").click(function (e) {
e.preventDefault();
$('#element_to_pop_up').bPopup();
$.post("page2.php", {val: $(this).closest('tr').find('td:eq(0)').text()}, function(returned_data){
// alert(returned_data);
$(e.target).closest("td").text(returned_data); // to replace button with score
});
});
</script>
on click of the button send the value of the first row to jquery and make a ajax call to second page and do the required calculations when ever by response of second page replace the button with result look for examples.
http://api.jquery.com/jQuery.ajax/
put your button in a span like this
<span id="result">
<button id="my-button">Get Score</button></span>
then in your response handling jquery put this
$("#result").html(you calculation result jquery variable);

utilize PHP variable in javascript

I just asked another question here: global variable and reduce database accesses in PHP+MySQL
I am using PHP+MySQL. The page accesses to the database and retrieve all the item data, and list them. I was planning to open a new page, but now I want to show a pop div using javascript instead. But I have no idea how to utilize the variables of PHP in the new div. Here is the code:
<html>
</head>
<script type="text/javascript">
function showDiv() {
document.getElementById('infoDiv').style.visibility='visible';
}
function closeDiv() {
document.getElementById('infoDiv').style.visibility='hidden';
}
</script>
</head>
<body>
<ul>
<?php foreach ($iteminfos as $iteminfo): ?>
<li><?php echo($iteminfo['c1']); ?></li>
<?php endforeach;?>
</ul>
<div id="infoDiv" style="visibility: hidden;">
<h1><?php echo($c1) ?></h1>
<p><?php echo($c2) ?></p>
<p>Return</p>
</div>
</body>
</html>
"iteminfos" is the results from database, each $iteminfo has two value $c1 and $c2. In "infoDiv", I want to show the details of the selected item. How to do that?
Thanks for the help!
A further question: if I want to use, for example, $c1 as text, $c2 as img scr, $c1 also as img alt; or $c2 as a href scr, how to do that?
Try this:
<?php foreach ($iteminfos as $iteminfo): ?>
<li>
<a href="javascript:showDiv(<?php echo(json_encode($iteminfo)) ?>)">
<?php echo($iteminfo['c1']); ?>
</a>
</li>
<?php endforeach;?>
Also, modify showDiv to take your row data:
function showDiv(row) {
document.getElementById('infoDiv').style.visibility='visible';
document.getElementById('infoDiv').innerHTML = row['c1'];
}
Basically, you have to consider that the javascript runs in the browser long after the PHP scripts execution ended. Therefore, you have to embed all the data your javascript might need into the website or fetch it at runtime (which would make things slower and more complicated in this case).
Do you want a single info area with multiple items listed on the page and when you click an item the info area is replaced with the new content??? or you want a new info area for each item??
I see something along the lines of the first approach, so I will tackle the latter.
<?php
//do some php magic and get your results
$sql = 'SELECT title, c1, c2 FROM items';
$res = mysql_query($sql);
$html = '';
while($row = mysql_fetch_assoc($res)) {
$html .= '<li><a class="toggleMe" href="#">' . $row['title'] . '</a><ul>';
$html .= '<li>' . $row['c1'] . '</li><li>' . $row['c2'] . '</li></ul>';
$html .= '</li>'; //i like it when line lengths match up with eachother
}
?>
<html>
</head>
<script type="text/javascript">
window.onload = function(){
var els = document.getElementsByClassName("toggleMe");
for(var i = 0, l = els.length; i < l; i++) {
els[i].onclick = function() {
if(this.style.display != 'none') {
this.style.display = 'block';
} else {
this.style.display = 'none';
}
}
}
}
</script>
</head>
<body>
<ul>
<?php
echo $html;
?>
</ul>
</body>
</html>

Categories