Popup show one time only - javascript

I have set session, and whant to display popup only once when user enters site, But my popup is displaying all time, Below is my code -
<?php
Mage::getSingleton('core/session')->setWall('1');
$wall = Mage::getSingleton('core/session')->getWall();
if($wall =='1'){ ?>
<script>
jQuery(document).ready(function() {
jQuery('#earn-reward-box').show();
//jQuery('#earn-reward-box').delay(000).fadeOut();
});
</script>
<div id="earn-reward-box-main" style="display:block">
<div id="earn-reward-box" class="xmus-box">
<div id="earn-reward-close"> </div>
<a href="<?php echo Mage::getBaseUrl()?>christmas">
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);?>wysiwyg/deal.png" />
</a>
</div>
<div id="earn-reward-overlay"> </div>
</div><script>
jQuery('#earn-reward-close').click(function(){
jQuery('#earn-reward-box-main').toggle();
});
jQuery('#earn-reward-close').click(function(){
jQuery('#earn-reward-overlay').toggle();
});
</script>
<?php
Mage::getSingleton('core/session')->setWall('1');
}
Mage::getSingleton('core/session')->unsWall();
?>

Set session variable as "display:block" once it shows up and is closed change it to "display:none" and set it at style="here is the session variable".

you could make it show for every new session by saving to the sessionStorage like this
jQuery(document).ready(function() {
if(window.sessionStorage.getItem('shown') === true ){
jQuery('#earn-reward-box').show();
}
});
And you can set your item to true when the user clicks on the overlay
jQuery('#earn-reward-close').click(function(){
window.sessionStorage.setItem('shown', true);
jQuery('#earn-reward-box-main').toggle();
});

Seeing from MVC, you need a Model(or State) stored somewhere to tell if the popup has shown already or not. For example you can use localStorage as the place to store this information:
localStorage.setItem('popup-shown', 'true');
And the next time you open this page, since localStorage remains, you can tell if it has been shown already or not:
localStorage.getItem('popup-shown') === 'true'
Then you can control the behaviors of you popup as you need.
sessionStorage might be also fine, but take care of this quote:
sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends.
https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage

Related

How to display the value of a php variable by clicking on a hyperlink

I want to display the balance of the user when he clicks on the hyperlink. the balance of the user is stored in a php variable. I am hoping that this can be done using javascript but I dont have much experience in javascript.
Below is my code:
$userbalance = $xyz[2];
echo "Your balance stands at ".$xyz[2];
This thing is working, but I want to display $userbalance by clicking on a link
I don't know what to put in the anchor tag.
Is it possible that by clicking on the hyperlink the value of the php varibale gets displayed?
Can I pass a function to href? or can I use onclick in some way?
Try this:
<a href="somepage.php?balance=<?php $balance = $xyz[2]; echo "Your balance stands at ". $balance; ?>" >Click</a>
By above method you can display balance in url at any pages. Then if you need to use that balance there just get that value with super global variable $_GET['balance'];
In the most simplest form, this can be done via storing the value in the "data-" attribute that HTML supports and then using Javascript to alert the value upon user's click.
<p>
Click to see your account
balance.
</p>
The PHP part of this would be just to echo the correct balance into the correct place in the HTML code above.
balance.
Example of the final HTML: https://jsfiddle.net/oh8jnmg2/1/
Niltish has given the right hint. But I wouldn't recommend putting a output string into a link, which gets displayed in the url. Since HTML is rendered through PHP, you can simply attach your value to the link by typing:
<a href="yourprintsite.php?balance=$userbalance>Click here to see your balance</a>
And then on yourprintsite.php, you just type:
if (!empty($_GET['balance')) {
echo "Your balance stands at " . $_GET['balance'];
}
And you're done.
This is a solution if you don't want to actually use two pages but still show new content and hide everything else:
$userbalance = $xyz[2];
echo `Your balance stands at <a href='javascript:{document.documentElement.innerHTML = ""; document.write(` . $xyz[2] . `);}'>see variable</a>`;
If you want just to display a new value below, then use:
$userbalance = $xyz[2];
echo `Your balance stands at <div id="myDiv"><a href='javascript:{document.getElementById("myDiv").innerHTML = ` . $xyz[2] . `;}'>see variable</a></div>`;
Do you can write next code, function getAttribute must you help
<script type="text/javascript">
function clickHanler(d){
alert(d.getAttribute("data-userbalance"));
}
</script>
<a
data-userbalance="21"
href="#"
onclick="clickHanler(this);">
Click to do something
</a>
First, let's start with the HTML, you need to create a <a></a> that routes to no where :
Click to see Balance
Then, in the Javascript part :
We will assign a method to handle the click on our link.
we need to use an Ajax call to get the balance from the balance.php page :
$("#linktobalance").on("click", function(){
$.post( "balance.php", function(balance) {
//In this part, the balance is the value returned from th PHP, you can do whatever with it, I'll alert it
alert( "The user balance is "+balance );
});
});
Note : we used jQuery, you can add it to your project by doing this :
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$("#showbalance").click(function(){
$("#balance").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
Show Balance
<div id="balance" style="display: none;">
Balance = 1000
</div>

onclick event with PHP SESSION variable happening on every page load

I'm trying to implement a logout mechanism, which would consist of a link to click that should set a SESSION variable to True, send the user to the login page where PHP will check the value of the same variable and destroy the cookie before regenerating the session if it's set to true. The problem is that what should happen as an onclick event happens every time I load the page (And I can confirm this by echoing the variable at the top of the page, which returns always 1) except for the first time, where instead I get an error message because the variable is still not set. Here's my code:
JavaScript:
<script>
function destroy_session(){
<?php $_SESSION["Logout"]=True; ?>
}
document.getElementById("logout").onclick=destroy_session;
</script>
HTML:
<li><i class="fa fa-sign-out fa-fw"></i> Logout
PHP:
if ($_SESSION['Logout']){
session_unset();
session_destroy();
session_start();
}
Am I doing something wrong? Is there a way to fix this?
js:
function profile_logout(){
$('#response').html("Please wait...");
$.post( "/logout.php", function( data ) {
$('#response').html(data);
});
return false;
}
html:
<li id="response"><i class="fa fa-sign-out fa-fw"></i> Logout
logout.php:
<?php
#session_start();
session_unset();
session_destroy();
echo "Logout success !";
?>
Note: don't forget add library jquery
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
this is for example :)

Temporarily changing HTML structure on the same page in PHP when submit button is clicked?

I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});

On toggle Hide/show

I have this code.
If a user press on lets say burger and add it into session basket. The reload of page doesn't open the current Window View(Toggle)
How can I make it open the current again on reload...
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
This is how to show/hide the text.
<div id="sandwich" class="hidden">
Here you go 1 </div>
<div id="burger" class="hidden">
Here you go 2 </div>
Things like this are not persistent across page reload / refresh.
There are two basic approaches to it:
Session cookie and session on server, communication via AJAX
Store all in a cookie
Both require some extra work, but it's unavoidable.
For the cookie part, there's a nice jQuery plugin called jquery.cookie.

FancyBox - "Don't show this message again" button?

I have FancyBox on a website that pops up when they visit and has some info inside it. I'd like to add some kind of button that the user can click, and it sets a cookie not to show the message for about a month or so.
I'm quite useless when it comes to things like this, so if anyone could walk me though what to do, that would be awesome.
Here's what I have so far. At the bottom I've added what I think could be an anchor for the proposed cookie ("noShow"), but I'm not sure if it would work like it is. I've loaded all the jQuery scripts before this for FancyBox, and after those it loads jquery.cookie.js too. If it matters, I'm using whatever the latest download for FancyBox 2 is.
<script type="text/javascript">
function openFancy() {
setTimeout( function() {$('#autoStart').trigger('click'); },1000);
}
$(document).ready(function() {
openFancy();
$('#autoStart').fancybox();
});
</script>
<!-- This is the popup itself -->
<a id="autoStart" style="display:none" href="#autoFancybox"></a>
<div style="display: none;">
<div id="autoFancybox" style="width: 800px">
<div>
<!-- My content for the Fancybox is here -->
<br />
<p style="font-size:10px" align="right">
<a id="noShow" href="#noShow">Don't me show this message again</a>
</p>
</div>
</div>
</div>
Thanks,
Liam.
Apart from your function that launches fancybox, make another that set the cookie's value and expiration time when the button is clicked :
function dontShow(){
$.fancybox.close(); // optional
$.cookie('visited', 'yes', { expires: 30 }); // set value='yes' and expiration in 30 days
}
... then validate the cookie and decide whether to launch fancybor or not :
$(document).ready(function() {
var visited = $.cookie('visited'); // create cookie 'visited' with no value
if (visited == 'yes') {
return false;
} else {
openFancy(); // cookie has no value so launch fancybox on page load
}
$('#autoStart').fancybox(); // bind fancybox to selector
}); // ready
... now the html of your button
<a id="noShow" href="javascript:dontShow()">Don't show this message again</a>
See working DEMO
There's a great jQuery plugin for cookie management which you should check out - https://github.com/carhartl/jquery-cookie
When a user hits your site, you can check your cookie to see if they've been there before. If they haven't then display your animation and set the cookie. If they have then don't run the animation.
From a glance at the jquery-cookie docs, you can set a cookie for 7 days like so:
$.cookie('visited', 'yes', { expires: 7 });
So your code might look like:
// Make sure DOM has fully loaded before running code
$(function(){
if( ! $.cookie('visited')){
// Your code here
} else {
$.cookie('visited', 'yes', { expires: 7 });
}
});

Categories