PHP alter and save cookie with starting value - javascript

I've been trying out working with cookies for the first time, with some mixed results. I want the visitor to be able to choose if the youtube videos autoplay or not by altering 1 and 0 in the embed url, and their choice saved in a cookie for when they return. On first visit the video should autoplay. I think my problem might be not knowing how to set the new value to the cookie properly?
At the moment I'm struggling with preserving the value when the visitor views the page after and/or setting the value in the first place at all. The site works almost as expected as long as ?autoplay=0 is kept in the URL to prevent autoplay.
I'd need to save the last chosen state of autoplay in a cookie, so thatthe visitor doesn't need to re-select it every time upon returning.
Ideal (but not neccessary) solution would be to not need the ?autoplay=0 except for maybe when the visitor clicks the link to make the switch (don't know if this is easy or complicated to achive – but in my mind the cookie could make the url variable useless?).
Index.php
<?php
// This might be very unneccessary,
// should probably look at the cookie and not the url?
// Can't figure out how though.
if($_GET['autoplay'] == "0"){
$autoplay = "0";
}else{
$autoplay = "1";
}
setcookie("autoplay",$autoplay, time()+3600*24);
$_COOKIE['autoplay'] = $autoplay;
?>
<!DOCTYPE html>
<html>
<body>
<button class="randomizerButton" data-href="data.php">Randomize</button>
<hr>
<div id="results">
<?php include('data.php'); ?>
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.randomizerButton').click(function(){
scriptUrl = $(this).attr('data-href');
$.post(scriptUrl, function(response){
$('#results').html(response);
});
});
});
</script>
</body>
</html>
data.php
<?php
$var = array(
array("Hello", "0wLljngvrpw", "10", "15"),
array("Hey", "TINASKjjNfw", "20", "25"),
array("Right in the dick! I shot you friend right in the di... Potatoes, Potatoes.", "rzU_fLcxIN0", "30", "35"),
);
// array_rand returns the INDEX to the randomly
// chosen value, use that to access the array.
$finalVar = $var[array_rand($var)];
echo('<iframe id="ytplayer" width="557" height="315"
src="http://www.youtube.com/v/'.$finalVar[1].'&start='.$finalVar[2].'&end='.$finalVar[3].'&autoplay='.$_COOKIE["autoplay"].'"
frameborder="0"></iframe>');
?>
Autoplay 1
|
Autoplay 0
<br><br>

you might want to set the cookie only when the url parameter is there ( when one of the linked have been clicked ). Just check if the parameter is set :
<?php
if (isset($_GET['autoplay']) || !isset($_COOKIE['autoplay'])) {
if($_GET['autoplay'] == "0"){
$autoplay = "0";
}
else{
$autoplay = "1";
}
setcookie("autoplay",$autoplay, time()+3600*24);
$_COOKIE['autoplay'] = $autoplay;
}
?>
The || ! isset ($_COOKIE['autoplay']) is because you wanted 1 as the default value if the user never choosed any yet. it means " if the cookie value doesn't exist "

Related

PHP, JS - Documenting and saving DATE/TIME to re-appear after browser closed

I currently have a sitation where I can click on an image and it will return a new image, and in the previous grid-item, it will return the day and time I clicked it.
What I want is to have this BUT where I also can see the updated image and clicked time after closing and re-opening the browser. - What is the easiest / quickest way to achieve this?
I feel like adding to my database would be a way forward, but if that is what I would need to do, how would I go about storing and out-putting the time based on the time I click?
(This is not intended to be a live site, or for others to see or use, so local quick-fixes are viable).
foreach ($flavours as $key => $flavour) {
echo "<div class='grid-container'>";
echo "<div class='item7'><p id='p3'>Sylus: </p></div>";
echo "<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>";
echo "</div>";
}
function cS(element) {
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: " + d;
}
else
{
element.src = "htts://i.i.com/k.jpg";
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: ";
}
}
Try this example using localStorage. This will find the <p> tag elements within the body, and then uses each element to get the id for reference.
I tried using a fiddle here, but the site has a security complaint with the localStorage.
Copy/paste this code to a file to give it a try. Note that you will likely need to update the moment.js reference in this code to match your file path.
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
After clicking an image (will need to replace with something real), open the browser's web inspector interface, click the Storage tab, and then expand the Local Storage in the list (see image below), and choose the file being tested.
There will be key/value pairs displayed. The keys are references to the <p> tag id's, and the value will have a label-date strings such as Sylus: Wednesday 22:28.
Once you see an entry, or two, being set to the storage, close and then reopen the browser tab. The <p> elements that had dates should be reloaded with their values from the storage.
The browser's Local Storage area should be similar to the image below:
save it to local storage, or a cookie with the exp. date too far in the future

Pass variables from Javascript to PHP - Popup/Modal Window

<html>
<head>
<script type="text/javascript">
function showdivv(el, idclicked) {
var iddd = idclicked;
var display = document.getElementById(el).style.display;
if(display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
</script>
<?php $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
<div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
<?php $variable = 4; ?>
<button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>
I'm trying to make a way when a person presses the button pass the variable, in this case ID, to JavaScript and then show the hidden div in PHP. It does not work, can someone help me? THX
If you're okay with the page reloading, you can simply do
window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');
If not, I absolutely recommend using JQuery as it makes Ajax queries a breeze.
Inside the <head> tags:
<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>
Upload the script to your own server for production purposes, obviously.
in the <body>, where you want the results from the PHP script to appear (skip this if you don't want output from PHP):
<div id="phpResult"><!--content to be set by ajax--></div>
and put this JS directly below this <div>:
function ajax_on_button_press(resultDiv, id) {
var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
$(resultDiv).load(phpUrl);
}
I have used example values here, but you can easily use variables from JavaScript like this:
var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";
To start the process, you need a button that runs this script. Change your button markup to
<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>
If I have understood you correctly, that should solve your problem.

Hide div content permanently

I want when the user click on submit button the content disappear (random text 3) until the user logs off. The JS works fine but, if I refresh the page, the content appears. Can anyone help me achieve this or can anyone convert my code to PHP so that I can use a session variable to achieve this?
<style type="text/css">
div.something{
/*random code;/*
}
</style>
<script type="text/javascript">
function hideSomething(){
document.getElementsByClassName("something")[2].style.display = "none";
}
</script>
<div class="something">random text 1</div>
<div class="something">random text 2</div>
<div class="something">random text 3</div><br />
<input type="submit" value="Disappear" onclick="hideSomething()" />
well the professional way is to record it on cookie or store in database with user information like IP or you can use rough way to just forward it to another page where that div not appear thou some dont allow cookies to store let me know which one you like and i will fill my answer with it sample
Use a cookie and store the status of the div there.
You can easily read and write a cookie using javascript.
A nice tutorial can be found here: http://www.w3schools.com/js/js_cookies.asp.
For example, in the hideSomething() function do the following:
document.cookie="display_div=true";
Then, when the page is loaded, call a javascript function that shows or hide the div based on the value of the cookie:
if(cookie_value == "true")
//Hide your div
else
//Show your div.
end
So first we create a form with a hidden text box, once user click on button Close Attendance the value of hidden textbox is submited and a session variable is created:
if(isset($_POST['hidden'])){
$_SESSION['closed'] = TRUE;
}
Then we check is session is set, if yes display attendance close, if not display content.
<?php if(isset($_SESSION['closed'])){
echo "attendance closed.";
}
else {
echo "<form name='test' action='attendance.php' method='post'>
<input type='hidden' name='hidden'/>
<button> Close Attendance </button>
</form>";
}
?>
try the following code, it should give you a very clear glimpse on how to do it.
<!DOCTYPE html>
<html>
<head>
<title>ZUUS: Ironman</title>
</head>
<script type="text/javascript">
function hideSomething()
{
document.cookie="hide_div=true";
myFunction();
}
function myFunction()
{
var cookie_value = getCookie("hide_div");
alert(cookie_value);
if(cookie_value == "true")
document.getElementById("test_div").style.display = "none";
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
</script>
<body onload="myFunction();">
<div id="test_div" style="background-color: blue;" onclick="hideSomething();">
this is a test
</div>
</body>
</html>

Having a cycled (interval) pictures on pre-loaded page through a directory

I am currently working for a library that would like to have a webpage designed digital signage. Most of it has been designed with widgets and through a program called Xcite Pro. I was unable to find any widgets that will allow me to do a slideshow from a directory that will cycle through. I do know the foundations to JavaScript and php.
I do not know how to take a directory and have JavaScript run through an entire directory into a array with picture values. I would like to use the setInterval() command but I seem to only know how to search through a directory by php. I did find a explanation on this site that tells me how to use php to search through and then pull all pictures to be shown. If i can get that to all go into an array that could be used with JavaScript on the site that would actually work fine. The link for that explanation is LINK.
Currently I am just using a folder called pics in my main file. So my directory is "pics" nothing to special. I have seen some things being talked about html5 using a new file search function but that sounds more like for finding particular files rather then taking the entire components of a folder into an array.
Edited 12/23/2013 Per PHPGlue Request and help.
So far the code that I have played with are:
Test html (Main Page)
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Basic XHTML Document</title>
</head>
<body>
<p>President Obama is from Hawaii</p>
<p><img id="scroller" alt="" src="pics/test.jpg" width="600" height="400"/></p>
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='pics\imagefun.php'></script>
</body>
</html>
Common js File in main directory with main page
// common.js
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
function gteIE(version, className){
if(IE >= version){
bod.className = className;
}
}
function E(e){
return doc.getElementById(e);
}
//]]>
Finally I have 2 pictures in a picture folder along with a imagefun php file.
// imagefun.php
<?php
$imgs = implode(array_merge(glob('*.png'), glob('*.jpg')), "', '");
echo "//<![CDATA[
var imgs = ['$imgs'], ni, iA = [];
for(var i in imgs){
ni = new Image; ni.src = imgs[i]; iA[i] = ni;
}
var pre = onload, iN = 0, iL = imgs.length-1, imgElementId = E('scroller');
imgElementId.src = imgs[0];
onload = function(){
if(pre)pre();
imgElementId.src = iA[0];
setInterval(function(){
if(iN >= iL)iN = 0;
imgElementId.src = iA[++iN];
}, 2000);
}
//]]>";
?>
PHPGlue-- Thank you for all the time that you have put into this. Really not trying to be a pain at all and I really do appreciate all of your patience. I have made sure to swap names based on my file structures. Based on what I see for the basic ideas of the code I would think it should work. As I said though when I load to test it, it will only show the picture I defaulted on the load and then never change. One thing that I have noticed is that if you take the code of the image fun php code and run just that, all it returns is an output of //=IL)iN = 0; imgElement.src = iA[++iN]; }, 2000; } //]]> If I am right then that string of output should be similar to the whole thing rather then just a fragment of a line like it is. I do believe if I am understanding the goal of this code we are having it spit out some code into the src location of the picture location?
Ultimately if possible I would like to have a cloud based file location that I could use to have an individual who works here store pictures in that file and then have the website pull all files in that location to be loaded to the page one at a time at an interval of about 15000ms. I would appreciated any comments or recommendations.
I ended up resolving this myself. Thank you for all the help.
This was a multi parter either way.
I created a php cycler code
Note** This code will actually run through all that was needed just in php. Sadly though as I wanted this to show up on a web page that would cycle on a timer I needed to use some javascript coding. This caused me to change parts of what was used. If you want to do the same thing you drop all code after you have created the pics array or you can even keep up to the point of the forwards and backwards array to be passed into javascript.
<?php
// create a variable to hold the directory location
$Dir = "..\Directory\pics";
// Variable to directory
$dirOpen = opendir($Dir);
// Need to start with a main array
$pics = array();
// Need two arrays for going forward and back
$forwards = array();
$backwards = array();
// Need variables for the program
$c = 0;
$d = 0;
$e = 0;
$i = 0;
$f = 0;
// Need to run through all files in folder and store into an array
while ($curFile = readdir($dirOpen))
{
if(strpos($curFile,'.jpg') !== false)
{
$pics[$i] = $curFile;
++$i;
}
}
closedir($dirOpen);
// declare variables to count previous opening of file
$a = count($pics); // number of pics in the folder
$b = count($pics) - 1; // need to account for starting at 0
// run through pics array fowards
while($f < $a)
{
$forwards[$f] = $pics[$f];
++$f;
}
// run through the pics array backwards
while($b > -1)
{
$backwards[$c] = $pics[$b];
--$b;
++$c;
}
// variables for the functions us
// use function for forward pics
/*function forward($array, $a)
{
$d = 0;
if($d == $a)
{
$d = 0;
return "pics/".$array[$d];
++$d;
}
else
{
return "pics/".$array[$d];
++$d;
}
}
function backward($backwards, $b)
{
if ($e == $b) // going to have a conflict with B becuase right now it should be at -1 or 0. need to compare to the value of -1 and have it reset to the max when reached.
{
}
}
*/
/*// Test the output of each array
foreach($pics as $imgs)
echo $imgs . "<br />";
foreach($forwards as $fors)
echo $fors . "<br />";
foreach($backwards as $backs)
echo $backs . "<br />";
*/
// $forwards and $backwards are the arrays to use for pics cycling
?>
To pass onto the java script I had to use the following code on another php page created to work with all html design of the main page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form name="myForm">
<p> </p>
<p> </p>
<p class="auto-style1"><img alt="" src="" id="pics" height="400" width="300"/></p>
<?php include 'imgCycler.php'; ?>
<script type='text/javascript'>
/* <![CDATA [ */
var forwards = <?php echo json_encode($forwards); ?>;
var backwards= <?php echo json_encode($backwards); ?>;
var max = <?php echo $a ?>;
var count = 0;
function changePic()
{
document.myForm.pics.src='pics/' +forwards[count];
//document.myForm.pics2.src='pics/'+backwards[count];
++count;
if (count == max)
{
count = 0;
}
}
var start = setInterval('changePic()',5000);
</script>
</body>
</html>
Again PHPGlue thank you for all the help you offered. Hope this is useful for anyone else that wishes to do something similar. Please let me know if there are any questions on the code.
Let's start by making a common.js file:
// common.js
//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
function gteIE(version, className){
if(IE >= version){
bod.className = className;
}
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now put the script below in the same folder you keep your images in:
// imagefun.php
<?php
$imgs = implode(array_merge(glob('*.png'), glob('*.jpg')), "', '");
echo "//<![CDATA[
var imgs = ['$imgs'];
for(var i in imgs){
new Image().src = imgs[i];
}
var pre = onload, iN = 0, iL = imgs.length-1, imgElement = E('imgElementId');
imgElement.src = imgs[0];
onload = function(){
if(pre)pre();
imgElement.src = imgs[0];
setInterval(function(){
if(iN > iL)iN = 0;
imgElement.src = imgs[iN++];
}, 2000);
}
//]]>";
?>
Change the imgElementId to yours inside E('imgElementId'). E('imgElementId') must refer to an <img id='imgElementId' /> tag.
Now on your HTML page, refer to this JavaScript page as PHP, at the bottom of your body:
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='path/imagefun.php'></script>
</body>
</html>
Also, change src='path/ to your image folder path, and add or subtract the correct , glob('*.jpg')s and the like, to suit your needs.
Notes:
E(id) gets your Element by id. bod.className changes to the <body class='njs'> to <body class='js'>, assuming you have the class attribute njs in your HTML body tag, for CSS without JavaScript (progressive enhancement). gteIE(version, className) is for Internet Explorer versions greater than or equal to a number passed as version, changing that version or greater's body class attribute to the className argument, because IE10+ won't accept HTML IE comments for CSS changes. imgfun.php caches the images into your Browser memory based on globs found in the folder the script resides in. Then, once these images are loaded into your Browser cache, they are cycled through using setInterval.

JS Variable Passing Via URL

I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".

Categories

Resources