Increasing PHP Variable onSroll without reloading the page - php

Ok,
I've seen a couple of solutions out there but I am looking for the most lightweight version to accomplish this following:
<?php
$number = 20;
$counter = 0;
$i = 1;
$friends = $facebook->api('/me/friends');
foreach($friends['data'] as $friend)
{
if ($counter++ == $number) {
break;
}
echo '<li id="'.$i++.'"><img src="http://graph.facebook.com/'.$friend['id'].'/picture"/>'.$friend['name'].'</li>';
}
?>
I want to be able to increase $number = 20 when the user scrolls past a speecific div.
So for instance I know I can use jQuery for the scrolling mechanism:
<script>
$('#20').waypoint(function(event, direction) {
if (direction === 'down') {
"Increase php variable to 40"
};
});
</script>
If you guys can provide any knowledge it would be much appreciated.
Thanks!

PHP runs server sided, meaning that the whole page gets computed before outputting. What you are doing is not possible the way you are approaching it.
There are two approaches that will work in this situation:
Output all the information to begin with, but hide it and when the user scrolls to whatever point show it programatically with Javascript
Use AJAX to do dynamic page generation.
AJAX allows you to make requests to the server from Javascript to request remote content. For example, you could grab the content of myFile.php?count=123 and output the result in a div.
See http://www.w3schools.com/ajax/ajax_example.asp for an example on how to use AJAX.

Related

How to put images returned by Flickr API into different pages?

I am trying to create a webpage to show some images returned by Flickr API. But there are thousands of images returned, so I can't put them on the same web page because then people need to scroll all the time. So I would like to put them into separate pages like we usually have, for example, "Page 1 2 3 next". But I don't know how to implement this. What I thought was using javascript to tell which page user chooses and then send this number to the API request. However, the API is handled by php and I don't know how to send a value from JS to PHP, so I haven't solved this problem yet. Could anybody give any thoughts! Thank you!
April
Here is the final solution for this problem:
php code for Flickr API call:
$page = 1;
$tag1 = "puppy";
$tag2 = "cute";
$flickrUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=blablablabla&tag_mode=all&tags=$tag1\',\'$tag2&per_page=20&page=$page";
The solution is instead of assigning the $page to a specific number, use the following statement:
$page = isset($_GET['page']) ? $_GET['page'] : 1;
By doing this, the php file will get the page retrieved via Flickr API directly.
And then I use some DOM elements for example as the links for "Next Page" and "Previous Page" to help you navigate through different pages.
echo "<p id=\"nav_bar\">";
$back_page = $page - 1;
$next_page = $page + 1;
echo "<a href='?page=1'>First Page</a>";
if($page > 1) {
echo "<a href='?page=$back_page'>« <strong>Prev</strong></a>";
}
// if current page is not last page
if($page != $page_count) {
echo "<a href='?page=$next_page'><strong>Next</strong> »</a>";
}
$last_page = $page_count;
echo "<a href='?page=$last_page'>Last Page</a>";
echo "</p>";
Finally, thank you for everyone who has helped.
I am unfamiliar with the flickr api so I don't know exactly how you would want to paginate things, but just looking at what you posted you could use ajax to request the API call. So in your h4 do something like:
<h4 id=\"num_imgs\">
Page <span data-page="1">1</span> |
<span data-page="2">2</span> |
<span data-page="3">3</span> |
<span data-page="4">4</span> |
<span data-page="5">5</span>
</h4>
Then do a jqueryish call like:
$('h4 span').click(function(){
getImages($(this).data('page'));
}
Then have a javascript image handler function that fetches the images and processes them/displays them to the user.
getImages(page){
var flickrUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=blablablabla&tag_mode=all&tags=$tag1\',\'$tag2&per_page=20&page="+page;
$.get(flickrUrl,function(data){
//PROCESS IMAGES
});
}
I hope that sort of setup makes sense. It seems to be what you are trying to do. You could make your page dynamic and still pass in the tags as well. Then you really don't need PHP to set up your page, but depending on how your user is selecting the tags, you may still do it via PHP. I would probably do the while thing via javascript.

Calling images dynamicly using javascript and php

i am new to Javascript and i have created the code below it works fine no problem at all however i want to know what is i want to pull the image dynamically using php and javascript from mysql database how can i refactor my code bellow. thanks in advance for your contribution.
var myimage = document.getelementById("mainImage");
var imageArray =["images/overlook.jpg","images/garden.jpg","images/park.jpg"];
var imageIndex =0;
function changeimage(){
myimage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
setInterval(changeimage, 5000);
One of several options.
Query the database for the column with the URL of the images.
$query = mysql_query("SELECT url FROM images");
Then something like this to get an array out of it:
$images = array();
while($row = mysql_fetch_array($query)){
$images[] = $row['url'];
}
Then generate this string (that you use in the Javascript provided):
var imageArray = ["images/overlook.jpg","images/garden.jpg","images/park.
using the array you retrieved from the database. You could use json_encode in PHP for this if you don't want to mess around with error prone string building.
$imagesAsJsonArray = json_encode($images);
Echo it. Done.
Not the most elegant of solutions. But it gives you something to play with. Check out a few PHP tutorials online and you'll soon get the hang of it.
Two choices:
Using PHP when your page is created, put an array of images in the page and use page-level javascript to cycle among them.
Using Ajax in the page, call from the page to the server to get the next image and then use client-side javascript to make that returned image visible on the page.

using jquery + <audio> w/ php/mysql to loop playback times

I've got a page with an iframe. The iframe is using jquery.scrollTo to detect the audio playback time and keep the contents, lyrics for example, linked to the right point in the audio.
Each line of text is being pulled from a mysql table. What I'm trying to do is to allow the user to click on a line in the <iframe> and have the audio in the parent page play at that point. Here's the code that grabs the times, which exists after the jquery that handles the other audio functions:
<?php
include 'mysqlt.php';
$entries=mysql_query("SELECT * FROM `database`.`table`") or die(mysql_error());
while ($ent = mysql_fetch_object($entries)) {
$segment = $ent->index;
$starttime = $ent->time;
$nextline = $ent->time2;
$length = ($nextline - $starttime); ?>
That same information is also duplicated in the iframe source page along with the individual lines of lyrics. The jquery that uses this info follows:
$("#iframe_id").contents().find("#button_in_iframe<?php echo $segment;?>").bind("click", function(){
audioplayer.currentTime = <?php echo $time;?>;
audioplayer.play();
}
<?php } ?>
This second part loops, echoed once for each each potential line in the iframe that can be clicked. #button_in_iframe<?php echo $segment;?> ends up as something like #button_in_iframe23 for the 23rd line.
I've got jquery loaded up in both the parent and the iframe. As far as I can tell, the syntax is what it should be. If I remove this bit of code, everything works normally. if it's in there, the basic audio functions on the normal controls I have set stop working. So this is not only not working, but it's causing everything else associated with the audio tag's controls to stop working as well. I know that any small error in the audio controls' jquery is enough to make it stop working, but in this case I'm not sure where the problem is.
Thanks in advance for any insights anyone might be able to offer.
update:
I've got it so it no longer crashes the audio tag. Now it's more an issue of the iframe's item not triggering an event. Here's the code now:
$('#iframe_id').contents().find("button.loop2").bind("click", function() {
alert ("test");
});
I'm not getting any console errors except for a Google Maps imbedded in the page in another location. When i click the <button> with class loop2 in the iframe, all of which exist, nothing's happening. That seems to be the root of the problem as it was earlier.
I figured out how to do it. I've set the loop on the parent to read as follows:
play<?php echo $segment; ?> = function(){
sfx.currentTime = sounds.getCueById(id).startTime;
sfx.play();
};
Then in the iframe's page, I've told each button to call parent.play<?php echo $segment;?>();
I'm not sure why finding the tags in the iframe didn't work, but no matter. This get's the job done.
Thanks, shanabus, for all the suggestions.
Would it work to use media cues?
Example:
var sfx = new Audio('sfx.wav');
var sounds = a.addTextTrack('metadata');
// add sounds we care about
sounds.addCue(new TextTrackCue('dog bark', 12.783, 13.612, '', '', '', true));
sounds.addCue(new TextTrackCue('kitten mew', 13.612, 15.091, '', '', '', true));
function playSound(id) {
sfx.currentTime = sounds.getCueById(id).startTime;
sfx.play();
}
You can find a better definition of the spec half way down the page here - http://dev.w3.org/html5/spec/Overview.html
So in your case, maybe something like:
$("#iframe_id").contents().find("#button_in_iframe<?php echo $segment;?>").bind("click", function(){
sounds.addCue(new TextTrackCue('<?php echo $segment; ?>', <?php echo $starttime; ?>, <?php echo ($starttime + $length); ?>, '', '', '', true));
var id = '<?php echo $segment; ?>';
sfx.currentTime = sounds.getCueById(id).startTime;
sfx.play();
}
Or maybe separate your logic into two loops. One for building the cues, then one for building/binding the click events.
Hope this helps!

Protect a generate image with php

I'm having a problem here and I think people here can help me.
I have a file that generates an image, ler.php, and the file that loads the images through a while, carregar.php.
I need to block direct access to the images generated by ler.php, tried to make a system like this session:
carregar.php:
<?
$_session['a'] = 1;
while($a != 50) { echo "<img src='ler.php?imagem=$a'>"; $a++; }
$_session['a'] = 0;
?>
ler.php:
<? if($_session['a'] == 1) { //load image } ?>
The result is the only loading the first image.
I'm trying to now use the $_SERVER ["PHP_SELF"], placing the IF of ler.php, what happens is I load it through <img src=''> she identifies as carregar.php.
Who has the best solution?
I've tried several ways with $_SESSION and it seems to not really work.
I could suggest two ways:
Easy to implement, less protective: in ler.php check that $_SERVER["HTTP_REFERER"] refers to "carregar.php".
A little bit more complicated: in carregar.php generate an unique code for each image you're going to output and store it in $_SESSION. Then pass the code to ler.php as a GET parameter. In ler.php check if the code exists in $_SESSION object, then generate an image and remove the code from $_SESSION.
I have a hard time identifying the problem, but your use of the session is going to lead to unexpected results:
You are adding 50 (I guess...) image tags to a page and right after you have added these tags, you set the session variable to 0.
The browser only loads a few files from the same server at the same time, so when the script is done and the first image is loaded, the browser is going to request the next image but that will fail as you have set the session variable to 0 already.
The only way to reliably set the session variable to 0 after all images have loaded, is an ajax request from your page that checks and triggers after all images have completely loaded.
Good! I managed to resolve one way and improvised without using AJAX:
ler.php:
<?php
if(isset($_SERVER["HTTP_REFERER"])) {
$check2 = (strpos($_SERVER["HTTP_REFERER"], 'carregar.php') > 0) ? true : false;
if(print_r($check2) != 11) {
// Blank
}
} else {
if(isset($_SERVER["HTTP_REFERER"]))
{
// Load Image
}
if(!isset($_SERVER["HTTP_REFERER"]))
{
// Blank
}
?>
So, the image only can be loaded into my page. Maybe...

Remembering text resizing across different pages on a web site using PHP SESSIONS

So after reviewing some tutorials on how to change text size and creating my own using PHP I was wondering how can I have my text size remembered across many different pages on my web site using PHP SESSIONS?
Here is the PHP text sizer code below.
$size = 100;
if(isset($_GET['i']) && is_numeric($_GET['i'])) {
$s = $_GET['i'];
}
if($s == TRUE){
$size = ($s * 1.2);
}
if(isset($_GET['m']) && is_numeric($_GET['m'])) {
$m = $_GET['m'];
}
if($m == TRUE){
$size = ($m * 0.8);
}
if(isset($_GET['n']) && is_numeric($_GET['n'])) {
$n = $_GET['n'];
}
if($n == TRUE){
$size = 100;
}
Here is the CSS code.
#content {
font-size : <?php echo $size; ?>%;
}
And here is the xHTML.
Increase<br />
Decrease<br />
Normal<br />
First all, make sure you out put session_start() on all pages, before any content is posted.
From here, you're able to set session variables (which will be saved into a session cookie typically).
So when your user clicks a link, PHP should set something like $_SESSION['i'] = $_GET['i']; and then when you visitor comes back to a page, you just see if $_SESSION['i'] has a value - if it does, use this value, if not, revert to default.
Check out this great tutorial: php sessions - why use them?
Just don't use $_GET variables, use $_SESSION vars instead. Be sure to include the relevant session_start() functions and all that.
As mentioned, you'll want to your the $_SESSION object instead of $_GET. You'll need to add a call to session_start() at the start of each page (check the examples on this link; will show you how to use sessions on a basic level). You may also want to take a look at Local Web Storage (browser-based) in HTML5. Check out this tutorial. It's quite easy to implement. Of course, not all browsers implement web storage, but it's pretty ubiquitous (Depending if you want to support < IE8)

Categories