Change background only on refresh with javascript - php

Iam loading pages in dynamically with PHP like so:
<div id="content">
<div id="fadein">
<?php
/// load page content
$pages_dir = 'content';
if(!empty($_GET['p'])) {
$pages = scandir($pages_dir, 0);
//delete . and ..
unset($pages[0], $pages[1]);
$p = $_GET['p'];
// only files that are in the array can be loaded
if (in_array($p. '.php', $pages)) {
include($pages_dir. '/'.$p. '.php');
} else {
echo 'Helaas deze pagina bestaat niet';
}
} else {
include($pages_dir. '/index.php');
}
?>
</div>
</div>
If you use the navigation at the top of my site the PHP loads the relevant content.
And i got this script at the bottom of my page to change the background image:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'../public/background/test2/1.jpg',
'../public/background/test2/2.jpg',
'../public/background/test2/3.jpg',
'../public/background/test2/4.jpg',
'../public/background/test2/5.jpg',
'../public/background/test2/6.jpg'
]);
var totalCount = 6;
function changeBackground()
{
var num = Math.ceil( Math.random() * totalCount );
backgroundUrl = '../public/background/test2/'+num+'.jpg';
$('body').css('background-image', 'url(' +backgroundUrl+ ')');
}
changeBackground();
But everytime different content is loaded, the script is executed...
I don't want that. I only want to change the background when the user refreshes the page. Not when different content is loaded when the user is navigating through the site.

As it is now (based on your comment), you are reloading the whole page when you really want to load only new content.
To be able to get the effect that you want, you should use ajax (combining php and javascript) to refresh only a part of your page when you hit a navigation link.
What you could do is (using jQuery for an easy introduction to ajax...):
separate your php script from the html so that you can call it separately and include it in your initial html;
attach an event handler to your navigation links, cancelling the default action (undo the click) and use jQuery's load method to replace your content with the new content (call your php script with the correct parameters).
As the javascript is located in the main html file, it will only execute your background script on the initial page load or page refresh.

If you are trying to manage this through JavaScript alone, then you can create a Cookie with an array of page visits, then on page load you can refer to that array to determine whether a user has visited that page already.

Related

php check if link clicked

The question is that how do i check if a link has been clicked?
+
+
(another document)
<?php
session_start();
$_SESSION['car'] = $_SESSION['car'] + 1;
$_SESSION['boat'] = $_SESSION['boat'] + 1;
header("Location: betalning.php");
?>
The first a tag add a car to the cart and the second a tag add a boat to the cart. How do i detect which one of the a tag that has been clicked, and if i now click on any of the a tags both a car and a boat will be added to the cart.
You can add GET parameters to the links:
Add car
And then in your PHP document:
if($_GET['add'] == 'car'){
$_SESSION['car'] += 1;
}
// etc...
This is basically the easiest way to pass data from one page to another using a link.
The concept that you should use. is Ajax.
Every click and others things with the browser only happens on the client ( browser ).
Then when you do click. The browser has send request to server.
The server, get values that you send from browser and it proccess.
Some simple may be:
// Html
<a id="linkone" href="laggtill.php">+</a>
<a id="linktwo" href="laggtill.php">+</a>
//Javascript
// Use jquery
$("#linkone").on("click", function(){
//function that send request to server
$.post('someurl.php', {})
.success(function(res){
console.log(res);
// If you stay here, the procces should be ended
})
// if you return false, the click dont redirect other window
// if you return true, the click redirect other window
return false;
});
// php file for first link
<?php
//capture values
// But only is a clic, then there is not values
session_start();
$_SESSION['car'] = $_SESSION['car'] + 1;
// If you want some simple, one file only works for one link
// For the other link, you should create other file same to this.
header("Location: betalning.php"); // With ajax dont use this line,
?>

Scroll through web images after thumbnail

I searched, but did not find the answer to this.
I have a website that displays hundreds of images in thumbnail format. I'm currently using php to display all of the images in thumbnail, then when the thumbnail is clicked upon to display the images in full-size.
What I would like to do is be able to click on a thumbnail and see the resulting full-size image, then at that point be able to scroll both back and forth through the full-size images without going back to the thumbnails.
As an added feature, when viewing the thumbnails, I would like to only load the ones that are currently displayed on the client page...ie - if the client screen resolution supports 20, then load only 20 and wait to load the rest on the client until the user scrolls down. The primary client in this use case is an iphone.
Thanks in advance!
you need to use a slider jquery plugin
Like
Jquery Light Box Plugin
When you click on the image, it should point to a new PHP file containing the full size image, or even better, load it in a new <div> with php you can get the client resolution with other tools
You actual have two seperate questions. One is to show the thumbs fullsize and be able to click to the next image. Almost every plugin to show images has that options. Personally i use fancybox, but pick anyone you like. To enable the next/prev buttons you need to group the images useing the rel tag.
Now to load the images per page, similar to google does it, you need to load it all in by javascript. Below is a setup of how you could do it. This is untested, as I did not have an image gallery at hand.
In the code below I load all images into the array at once, which is not perfect when you have a lot of images (like 1000+). In that case your better of using AJAX to load a new page. But if you have a smaller amount of images, this will be faster.
<script>
//simple JS class to store thumn and fullimage url
function MyImage(thumbnail, fullimage, imgtitle) {
this.thumb = thumbnail;
this.full = fullimage;
this.title = imgtitle;
}
//array that holds all the images
var imagesArray = new Array();
var currentImage = 0;
<?php
//use php code to loop trough your images and store them in the array
//query code to fetch images
//each row like $row['thumb'] and $row['full'] and $row['title'];
while ($row = mysqli_fetch_assoc($result))
{
echo "imagesArray.push(new MyImage('".$row['thumb']."', '".$row['full']."', '".$row['title']."'));";
}
?>
//the thumb width is the width of the full container incl. padding
//In this case I want to use 50x50 images and have 10px on the right and at the bottom. Which results in 60x60
var thumbWidth = 60;
var thumbHeight = 60;
var screenWidth = $('body').width();
var screenHeight = $('body').height();
var maxImagesPerRow = Math.round(screenWidth / thumbWidth);
var maxImagesPerCol = Math.round(screenHeight / thumbHeight);
var totalImagesPerPage = maxImagesPerRow * maxImagesPerCol;
//function to load a new page
//assuming you use jquery
function loadNextPage() {
var start = currentImage;
var end = currentImage + totalImagesPerPage;
if (end >= imagesArray.length) {
end = imagesArray.length - 1;
}
if (end<=start)
return; //last images loaded
$container = $('#thumbnailContainer'); //save to var for speed
$page = $('<div></div>'); //use a new container, not on stage, to prevent the dom for reloading everything on each iteration of the loop
for (start;start<=end;start++) {
//add a new thumbnail to the page
$page.append('<div style="margin:0;padding:0 10px 10px 0;"><a class="fancybox" rel="mygallery" href="'+imagesArray[start].full+'" title="'+imagesArray[start].title+'"><img src="'+imagesArray[start].thumb+'" alt="" /></a></div>');
}
currentImage = start;
//when all images are added to the page, add the page to the container.
$container.append($page);
}
$(function() {
//when loading ready, load the first page
loadNextPage();
});
//function to check if we need to load a new page
function checkScroll() {
var fromTop = $('body').scrollTop();
//page with a 1-based index
var page = 1 + Math.round(fromTop / screenHeight);
var loadedImages = page*totalImagesPerPage;
if (loadedImages==currentImage) {
//we are scrolling the last loaded page
//load a new page
loadNextPage();
}
}
window.onscroll = checkScroll;
</script>
<body>
<div id='thumbnailContainer'></div>
</body>

Using .one() with .get()

QUESTION: What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?
MOST RECENT EDIT:
solution
<script>
$(document).ready(function(){
$('.tree li a').one("click", function() {
var currentAnchor = $('.tree li a').attr('href');
if(!currentAnchor){
var query = "page=1";
}
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
alert ("page=" + page);
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
return false;
});
});
</script>
More Specifically:
I'm using Javascript and PHP to load some external PHP pages as sections in my main template.
I'm using a switch and append() so the included files keep appending. I need every file to be able to be appended ONLY ONCE. Here is the scenario as I'd like it to happen
1) downloads link is clicked
2) downloads.php appears
3) errors link is clicked
4) errors.php appears below downloads.php
5) downloads link is clicked again
6) page just scrolls up to top of downloads.php
I need the same functionality as the example on the documentation page of .one() where every div can be clicked only once.
I also looked at Using .one() with .live() jQuery and I especially liked the approach used in the accepted answer.
Iried using boolean flag as suggested below but all it did was limit my consecutive clicks on the same link to one. So if I click one link 1 multiple times it'll show page 1.php only once but if I click on link 1, then link 2, then link 1 again it will display page 1.php, then append page 2.php and append another page 1.php.
I'm starting to think that the setInterval is wrong and I may use .one() for the whole checkAnchor() function and bind it to the <a> tags. I tried this but it's not working either :(((
core.js - using .one()
var currentAnchor = null;
//$(document).ready(checkAnchor);
//Function which chek if there are anchor changes, if there are, sends the ajax petition checkAnchor
$("a").one("click", function (){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
}
});
The other thing I liked as an approach is adding the names of the pages to an array and then checking that array to make sure the page wasn't displayed yet. I managed to fill up an array with the page names using .push() but I hit a dead end when looking up for a value in it. If you have an idea how that's supposed to look like that'd be very helpful as well.
core.js
///On load page
var contentLoaded;
$().ready(function(){
contentLoaded = false;
setInterval("checkAnchor()", 300);
alert (contentLoaded);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
alert (contentLoaded);
if (!contentLoaded){
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
alert (contentLoaded);
}
contentLoaded = true;
}
}
here is my
callbacks.php
<?php
//Captures the petition and load the suitable section
switch($_GET['page']){
case "4100errors" :
include 'template/4100errors.php';
break;
case "4100downloads" :
include 'template/4100downloads.php';
break;
}
?>
And my main file
4100.php
<?php
include 'template/header.php';
include 'template/4100menu.php';
include 'template/log.php';
include 'template/links.php';
include 'template/4100breadcrumbs.php';
?>
<div class="left-widget">
<div style="display:none; position:absolute; top:-9999; z-index:-100;">
</div>
<div id="side-nav-bar" class="Mwidget">
<h3>Contents</h3>
<ul class="tree">
<li><a href="#4100downloads" class="links" >Downloads</a> </li>
<li>Error Troubleshooting</li>
</ul>
</div>
</div>
<div id="content" style="margin-top:100px; margin-left:300px;">
<?
switch ($_GET['page'])
{
case "4100downloads": include 'template/4100downloads.php'; break;
case "4100errors": include 'template/4100errors.php'; break;
}
?>
</div>
</body>
</html>
4100dowloads.php
Downloads test page
4100error.php
Errors test page
Also you can look at the test page here http://period3designs.com/phptest/1/4100.php
"What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?"
.one() and live() really have little to do with $.get. They're only for event handling.
If you intend to run the code every 50ms as you are, but want to replace the current content, then use .html() instead of .append().
$("#content").html(data);
This will overwrite the old content.
I assume you're aware of this, but just to be sure, your code is running at an interval because of this...
$().ready(function(){
setInterval("checkAnchor()", 50); // better--> setInterval(checkAnchor, 50);
});
If you only want it once on document load, then do this...
$(document).ready(checkAnchor);
Just use a boolean flag to determine if you loaded the data yet or not. Set it to false on page load, and just after the call to $.get set it to true. Then, wrap your $.get with an if (!contentLoaded) { $.get ... }.
That way you will execute the $.get only once.
BTW: $.one is used to bind an event to an element, that will execute only once and then unbind it self from it.

AJAX pagination solution for PHP

Right now I use a pagination system that requires url like
http://mypage.com/index.php?page=1
http://mypage.com/index.php?page=2
http://mypage.com/index.php?page=3
http://mypage.com/index.php?page=4
etc...
So it uses $_GET method to find out what page the user is on.
I decided to switch most of my website to ajax and came over a problem. When I use Ajax to load new content on a page the url stays the same all the time e.g. http://mypage.com/index.php . Therefore pagination system I use is useless.
I was not able to find efficient AJAX pagination systems, (e.g some where lagy, most required user to scrol to the tiop each time he / she clicked on a next page, because they stayed at the bottom of the page when they clicked next page. etc...)
So I decided to ask you lot if anyone has an efficient pagination solution that works with ajax.
Example of what needs to be paginated:
$sql = mysql_query("SELECT * FROM myMembers WHERE username='$username' LIMIT 1") or die (mysql_error("There was an error in connection"));
//Gather profile information
while($row = mysql_fetch_assoc($sql)){
$username = $row["username"];
$id = $row["id"];
$data_display .= '<b>'.Name.'</b> has an id of <span style="color: f0f0f0;">'.$id.'</span>';
}
<!doctype>
<html>
<?php echo "$data_display"; ?> //and I need to paginate this entries
</html>
jQuery that loads new content from different pages into #content div
<script type="text/javascript">
function viewHome(){
$('#woodheader').load("inc/home_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/home.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewAbout(){
$('#woodheader').load("inc/about_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/about.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewProducts(){
$('#woodheader').load("inc/products_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/products.php", function () {
$(this).hide().fadeIn(700)
});
}
</script>
Pagination is not as hard as you can think, you can use jQuery's load() function to load content into an element with the page's content.
So for example you have:
<div id="page-content"></div>
Page 1
Page 1
Page 3
<script>
$.ready(function(){
var currPage = <?=$pageNumber; ?>; // The page number loaded on page refresh
$('#link1,#link2,#link3').onclick(function(){
// Get the first number inside the id
var pageNum = parseInt($(this).attr('id'));
// Don't load the same page
if(currPage == pageNum) return;
// Show loading animation or whatever
// Load the page using ajax
$('#page-content').load('pages.php?page='+pageNum, function(){
// End loading animation
currPage = pageNum;
});
return false; // Important for not scrolling up
});
});
</script>
Regarding the url, you have three options to choose from when a user clicks a page link:
Just load the page with no changing of the url
Use the HTML5 history.pushState(see MDN resource) if supported and with option 3 as fallback for unsupported browsers
Use #page1, #page1 etc. as the href value of the links so that the user knows on what page they are on and parse the value of the url in php:
$uri = explode('#page', $_SERVER['REQUEST_URI']);
$pageNumber = intval($uri[1]);
I would create a index.php that doesn't load any $data_display initially.
Internally in javascript I would keep a variable named $page that would initially equals 1.
After load it would make a ajax call to names.php?page=$page and pass the results to a handler that presents it to the user.
Then on the links to "back" and "next" I would put a javascript function that first sets $page to the previous or next number, then calls names.php?page=$page and pass the results to the same handler.

how i can i change the content of a page without refreshing

how i can i change the content of a page without refreshing.I know we need to use hidden frames for this but all the tutorials i have come across teach this only for HTML files what if the content is returned from a PHP file how do i do it in such a case? what should the php file echo or return?
You will have to use Ajax for that, have a look at this tutorial:
AJAX Tutorial
If you use a hidden frame, the content won't be displayed (hence "hidden"), I think you just mean to use an iframe. But this doesn't fit your description of "without refreshing", since you have to refresh the frame.
When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It's the same whether the PHP file is loaded inside a frame or not.
I use this method for a lot of my websites and so does Google. If you want to get data from a PHP file and then dynamically update the page you need to "import" the PHP file somehow without the entire page being redirected, or using iframes (which works too but is a lot messier). The way you do this is to import the file as a "javascript" file.
The following code demonstrates a form called "testform" and a text input called "userpost".
When you submit the form, it will import a file, and then update div "outputText" with whatever you entered... and wait for it... all without the page being redirected at all or refreshed!
I have included a lot of extra functions to show how you can access all of your functions on the same DOM unlike if you use frames where you have to use "top.object" or what not
index.html
<html>
<head>
// Get objects by their id. We will use this in the PHP imported file
Get = function(id) {
return (!id) ? null : (typeof id == "object") ? id :
(document.getElementById) ? document.getElementById(id) :
(document.all) ? document.all[id] :
(document.layers) ? document.layers[id] : null;
}
// Formats a string so it does not break in a URL
String.prototype.formatForURL = function() {
var str = escape(this.replace(/ /gi, "%20"));
str = str.replace(/\&/gi, "%26").replace(/\=/gi, "%3D");
str = str.replace(/\//gi, "%2F")
return str;
}
String.prototype.contains = function(str) {
return (!str) ? false : (this.indexOf(str) > -1);
}
Object.prototype.killself = function() {
this.offsetParent.removeChild(this);
}
// Import the script
ImportScript = function(js) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
script.setAttribute("charset", "utf-8");
// we add the is tag so can delete the "js" file as soon as it executes
script.setAttribute("id", "import_" + head.children.length);
script.setAttribute("src", js + (js.contains("?") ? "" : "?") + "&is=" + head.children.length);
head.appendChild(script);
}
// Get and send value to php file
sendInfo = function() {
var file = "js/myFile.php?userpost=";
file += document.testform.userpost.value.formatForURL();
ImportScript(file);
}
</head>
<body>
<div>
<form name=testform onsubmit="sendInfo(); return false">
<input type=TEXT name=userpost />
<input type=SUBMIT value=Go />
</form>
</div>
<div id=ouputText>
This text will be replaced by what you type
and submit into the form above
</div>
</body>
<html>
js/myFile.php
<?php
// Here you can now use functions like mysql_connect() etc. even exec()
// ANYTHING! Save them into variables and output them as text which goes
// Straight into the javascript! e.g. :
// $con = mysql_connect("localhost", "username", "password");
// if($con) {
// ... code to retrieve data and save into $variable
// }
// print "alert(\"$variable\");"; // this alerts the value in variable
if(isset($_GET['userpost'])) {
$userpost = $_GET['userpost'];
?>
Get("outputText").innerHTML = "<?=$userpost; ?>";
<?php
}
?>
// Clear text area
document.testform.userpost.setAttribute("value", "");
// Remove the file from header after info is changed
Get("import_<?=$_GET['is']; ?>").killself();
If I had typed in "Hello World" into text input "userpost" then
div "outputText" would be filled with the words "Hello World"
deleting what was previously there, and the text input will be cleared
Hidden frames is one design pattern that is a part of the overall AJAX design pattern. This is an extreme high-level overview, but this is essentially how it works:
Javascript in your HTML page makes a request to your PHP script by using an XMLHTTPRequest object, or a hidden frame or iframe. This is usually done asynchronously, so you can continue to work with your HTML page while the request is being made.
The data is returned to your Javascript. At this point, you can then manipulate the page, and update data on the page using various DOM methods.

Categories