This might seem easy enough for the lovely experts here at SO :) but I can't find a decent answer/question about this on SO or google. Pls help. :)
How do i display a current value of a php variable in realtime via AJAX/js/jQuery
Basically im trying to do an E-commerce site and I am storing the shopping cart contents using a session and displaying it with an echo statement counting how many contents is currently in the basket, however when they are on a certain product and tried adding it in the cart, the value of the cart doesn't echo the added item until there is a page refresh, so i need something like an AJAX to display the updated value of the session when an item is added without having a page refresh.
Thank you so much.
Here is my code snippet for the cart as a sample:
// Assign shopping cart ($_SESSION['cart']) into variable
$basket = count($_SESSION['cart']);
And for displaying:
<!-- Display contents of the shopping cart -->
<ul id="basket" class="clearfix">
<li class="top">
<a href="checkout.php" class="top_link">
<span>Items: <? echo $basket ?></span>
</a>
</li>
</ul>
Thank you so much.. kindly provide a sample code on how to achieve this (either js or jQuery) and would help as well for best practices in dealing with this type of scenario.
First solution (based on your request - BAD IDEA)
get-count-items.php
<?php
session_start();
die(count($_SESSION['cart']));
?>
Javascript
<script>
setInterval(function(){
$.post('get-count-items.php', {}, function (total_items){
$('#total-items').html(total_items);
});
}, '1000');
</script>
HTML
<ul id="basket" class="clearfix">
<li class="top">
<a href="checkout.php" class="top_link">
<span>Items: <span id="total-items"><? echo $basket ?></span></span>
</a>
</li>
</ul>
This javascript will make a request to server at each 1 second.
Second solution (event on button "Add to cart")
add-to-cart.php
<?php
session_start();
// code for add to cart...
die(count($_SESSION['cart']));
?>
Javascript
<script>
$('.add-to-cart').click(function(){
$.post('add-to-cart.php', {}, function (total_items){
$('#total-items').html(items);
});
return false;
});
</script>
HTML
<ul id="basket" class="clearfix">
<li class="top">
<a href="checkout.php" class="top_link">
<span>Items: <span id="total-items"><? echo $basket ?></span></span>
</a>
</li>
</ul>
<a href="" class="add-to-cart">Add to cart</>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am starting a cart session on my cart page but cart dropdown is not updating with a count until I refresh the page. I just want to update the div without reloading.
I am using foreach but it doesn't work. What should I do now.
<?php
session_start();
require_once("product.php");
?>
<li class="header-cart dropdown default-dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
<div class="header-btns-icon">
<i class="fa fa-shopping-cart"></i>
<?php
if(isset($_SESSION['cart'])){
?>
<span class="qty"><?php echo count($_SESSION['cart'])?></span>
<?php
}else{
?>
<span class="qty">0</span>
<?php
}
?>
</div>
<strong class="text-uppercase">My Cart:</strong>
<br>
<span>Shop Now</span>
</a>
<div class="custom-menu">
<div id="shopping-cart">
<div class="shopping-cart-list">
<?php
#$cart = unserialize(serialize($_SESSION['cart']));
$total = 0;
if($cart){
foreach($cart as $k=>$v)
{
$total += $v->price * $v->quantity;
?>
<div class="product product-widget">
<div class="product-thumb">
<img src="<?php echo $v->img;?>" height="50" width="60" alt="">
</div>
<div class="product-body">
<h3 class="product-price"><?php echo $v->price;?> <span class="qty">x1</span></h3>
<h2 class="product-name"><?php echo $v->name;?></h2>
</div>
<button class="cancel-btn" style="margin-right:8px;"><i class="fa fa-trash"></i></button>
<?php }
?>
<div class="shopping-cart-btns">
<button class="main-btn">View Cart</button>
<button class="primary-btn" style="margin-left:15px;">Checkout <i class="fa fa-arrow-circle-right"></i></button>
</div>
<?php
}
else{
echo '<p style="color: red;">No Product is added in your cart</p>';
}
?>
</div>
</div>
</li>
I want to update the cart div when I click on Add to cart.
As you have not provided enough code to work with, I will post the concept and hope you will be able to do it, also comment if you have any more doubts I'm always open to help
So firstly you need to write a function that asynchronously fetches
the data - Which means it fetches the data without having the page to
reload.
So you need to write the PHP code in a PHP file instead of in the HTML page, for example,
cart.php or where ever you have written your query to fetch the count
of the cart from database.
Once you have done that then you need to write an AJAX call to the
button of Add to Cart, So when you click on add to cart, it triggers
the ajax request and fetches the data from the backend which is
passed from your cart.php
for example , write this code inside your add to cart button
fetch("cart.php")
.then(res=>res.json)
.then(res=>{
//You will get the count here and just append it inside the tag where your count is displayed
//For example :
count.innerHTML = res
})
Don't forget to json_encode($count); in the PHP file so that you can receive the data in JSON format
Here in My View:
<div class="dropdown">
<button class="btn dropdown-toggle" type="button" data- toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<?php
foreach($site as $sites)
{
echo '<li >"'.$sites->site_title.'" </li>';
}
?>
</ul>
</div>
<?php
}
?>
i want to redirect when user click on $sites->site_title
but how it working is it automatically redirects to url
enter code here"<li><a href='shop/viewSiteId?id=".$sites->site_id."'>".$sites->site_title."</a></li>";
and get that id by using GET method
A redirect is the programmatic way to send a browser to a URL. In other words, a call to redirect is like clicking a link. They are not intended to work together in the way you have tried.
<?php
foreach($site as $sites) : ?>
<li>
<a href='<?= base_url("shop/viewSiteId?={$sites->site_id}"); ?>'><?=$sites->site_title; ?></a>
</li>
<?php endforeach;
If you are not familiar with the syntax, know that <?= is the shortcut way to write <?php echo
I've also used PHP Alternative Syntax for Control Structures and dropped in and out of the PHP processor a bunch of times. For me, that is the easier way to read and write this kind of thing. (Your mileage may vary.)
I'm working on a simple project which has a requirement to show a particular block of html by passing an div id to that url.
I have tried so many solutions, but none of them worked for me.
Here is my code.
<div class="row">
<a onclick="redirect_tooltip();">
<i class="fa fa-question-circle" aria-hidden="true"></i>
</a>
</div>
Whenever I click the icon it calls a Javascript function, through that function I tried to pass a url with another page division id
function redirect_tooltip()
{
var source_type = $("#_src_type").val();
if(source_type == "source")
{
window.location.replace(base_url+'/help/tooltip#rtmp_4');
//I have already difined the base url
}
}
My html code:
<div id="rtmp_4">
<h4>Some Title</h4>
<h5> <?php echo trim($tooltip_rtmp_server[1]);?></h5>
<p> <?php echo trim($tooltip_rtmp_server[3]);?> </p>
<h5> <?php echo trim($tooltip_rtmp_stream_name[1]);?></h5>
<p> <?php echo trim($tooltip_rtmp_stream_name[3]);?> </p>
</div>
I need to display only the rtmp block whenever the url executes. Please give me a suggestions like where I am doing the mistake.
I have a div that includes shoutbox posts. I'm using jQuery and ajax to change the pages within the div. However, when the page changes, it loses the link to the javascript file so that the next time I try to change the page it actually continues with the link action instead of doing the ajax in the background. Then after that it's back to normal and it alternates back and forth between being linked to the file and not.
Also before, it was rendering the whole page so that my layout was being displayed on the refresh instead of just the shoutbox posts. I'm guessing that finally getting it to refresh without re displaying the whole layout again is what's causing it to lose the connection to the javascript file.
This is the code for the posts. The shoutbox_arrows contains the links to change the page. refresh_me is what I'm loading into my div to refresh the content.
<div id="shoutbox_arrows">
<?php $current_page=s tr_replace( '?', '#', getURI(fullURL())); ?>
<ul class="no_dots">
<li id="first_page"><<
</li>
<li id="previous_page"><
</li>
<li><strong>Pg#<?php if ($page > $last_page) {echo $last_page;} else {echo $_SESSION['shoutbox_page'];} ?></strong>
</li>
<li id="next_page">>
</li>
<li id="last_page">>>
</li>
</ul>
</div>
<div id="shoutbox" class="custom_scrollbar">
<div id="refresh_me">
<?php if (sizeof($shouts)==0 ) { ?>
<p>There are no posts.</p>
<?php } foreach ($shouts as $shout) { foreach ($shout as $k=>$v) { $shout[$k] = utf8_encode($v); if ($k == 'guest') { $shout[$k] = ucwords($v); } } ?>
<div class="post_info">
<div class="left">
<?php if ($shout[ 'user_id']==n ull) {echo $shout[ 'guest'];} else { ?><?php echo ucwords(userinfo($shout['user_id'])->username); ?>
<?php } ?>
</div>
<div class="right">
<?php time_format($shout[ 'created_at']); ?>
</div>
</div>
<p class="post_comment" id="shoutbox_comment_<?php echo $shout['id']; ?>">
<?php echo $shout[ 'comment']; ?>
</p>
<?php if (!$shout[ 'last_edited_by']==n ull) { ?>
<p class="last_edited">Edited by
<?php echo ucwords(userinfo($shout[ 'last_edited_by'])->username); ?>
<?php time_prefix($shout[ 'updated_at']); ?>
<?php time_format($shout[ 'updated_at']); ?>.</p>
<?php } ?>
<?php if (current_user()) { if (current_user()->user_id == $shout['user_id'] or current_user()->is_mod) { ?>
<p class="post_edit"> <span class="edit" id="<?php echo $page; ?>">
<a id="<?php echo $shout['id']; ?>" href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
edit
</a>
</span> | <span class="delete" id="<?php echo $page; ?>">
<a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
delete
</a>
</span>
<span class="hide" id="<?php echo $page; ?>">
<?php if (current_user()->is_mod) { ?> | <a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
hide
</a><?php } ?>
</span>
</p>
<?php }} ?>
<?php } ?>
</div>
</div>
This is the page that my ajax request is going to.
<?php
if (isset($data['page'])) {
$_SESSION['shoutbox_page'] = intval($data['page']);
}
$redirect = ltrim(str_replace('#', '?', $data['redirect']), '/');
redirect_to($redirect);
Div that contains the content to be refreshed.
<div id="shoutbox_container">
<?php relativeInclude( 'views/shoutbox/shoutbox'); ?>
</div>
jQuery
$('#shoutbox_arrows ul li a').click(function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
So I guess to clarify the issue:
The shoutbox_container displays posts for the shoutbox. The page is controller by a session that gets passed as a variable to get the correct chunk of posts to show. Clicking on the links in shoutbox_arrows sends an ajax request to a page which changes the session variable. The div that contains the post itself (refresh_me) as well as the arrows (for the links) get refreshed. After changing the page once, the shoutbox is no longer connected to the javascript file so when you click to change the page again, instead of an ajax request, the page itself actually changes to the link.
Any ideas how I can fix this? I've spent a lot of time on this and it's getting rather frustrating. I feel like I could just settle for it as it is now but it's bugging me too much that it's not working exactly how I intend (although generally it works in terms of changing the pages).
Also just a note, I used jsfiddle to tidy up the code but it looks like it did some funky stuff (looking just at $current_page=s tr_replace). lol. So there aren't any syntax errors if that's what you're thinking. ><
Also I was going to set up a fiddle but I don't really know how to handle links in it so it would have been useless.
The issue is that you bind the click handler to the a tags on document ready (the jQuery code you provided). So when you replace the content of #shoutbox_arrows you remove the click handler you previously attached since those original handlers are removed from the DOM along with the original elements.
You need to use the jQuery .on() method and event bubbling. This will attach the handler on a parent element that will not be removed in your content replace and can continue to "watch" for the event to bubble up from it children elements.
Try replacing your jQuery code with this:
$('#shoutbox_arrows').on('click', 'ul li a', function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
For performance, you should add a class to the a, and targeting it directly with $('a.aClass')
Good ways to improve jQuery selector performance?
This may seem like a duplicate question but I have googled and search stackoverflow how an a anchor tag would act like as a submit that would fit on the website that I am trying to do.
I have this code on my right panel navigation:
<div class="content clearfix">
<div class="left_column">
<div class="product_menu">
<? if($_SESSION['logged_in'] == 1) {
$customer_panel = '
<div class="customer_nav">
<h1 class="customer_nav_name">Hello ' . $_SESSION['fname'] . ',</h1>
<ul class="clearfix">
<li>View Profile</li>
<li>Update Information</li>
<li>
<!-- this is where i would like the signout button to act as a submit
i have left it plane to start from scratch -->
Sign Out
</li>
</ul>
</div>';
echo $customer_panel;
}?>
<h2><span>Product Categories</span></h2>
<ul id="prod_nav" class="clearfix">
<li class="top"><span>Processed Meat</span></li>
<li class="top"><span>Ready Made</span></li>
<li class="top"><span>Siomai & Siopao</span></li>
<li class="top"><span>English Pork Snacks</span></li>
</ul>
</div>
And here is my usual code when i use a submit button and not an anchor tag to make a POST method:
if(isset($_POST['signout'])) { // logout button
// Clear and destroy sessions and redirect user to home page url.
$_SESSION = array();
session_destroy();
// Redirect to where the site home page is located -- Eg: localhost
header('Location: http://localhost/');
}
I have read many of this questions but I don't know jQuery or how to achieve this using javascript.
I also tried using this solution:
<form id="signout" action="index.php" method="post">
Sign Out
<input type="hidden" name="signout" value="signout"/>
</form>
that I kinda found from here at stackoverflow.
The problem about this is that if I include the onclick="" , the whole page does not show. but if i remove it, the page comes back to normal. - it doesn't work inside an <li> element.
It might sound basic, but it would help me and other new starters to understand how to make it possible. Thank you very much. :)
Try this,
STEP 1 :
Put the following scripts in your html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(function() {
$('.signout-btn').click(function() {
$('#signout').submit();
});
})
</script>
STEP 2 :
Add an attribute class="signout-btn" to anchor tags, which you want to trigger the form submission.