I am working on making a album-viewer like facebook.
I have made the "setup", you can see the photo, what album its in and so, now I would like to make the "next" "previous" buttons work.
I have seen them using preloading while viewing a current, and i wish to accomplish something like that.
But first of all, how can I make the "next"? What are the procedure to make the "next" work.
With this I mean how should I code it, so it knows which picture is next? I would like to sort it from the date(order by date), so the next should be newer than the current date, and previous older than the current date.
My database looks like this:
album
id uID title
album_photos
id aID uID photo date
aID holds the id of the album(album ID), uID holds the id of the user(userID).
I also want to make use of javascript too. Make an ajax request, instead of refreshing whole page.
So my question is:
What is the procedure of making next/prev button, if I would like to make it work after date DESC, how does the javascript look like? An ajax request to file.php, that are grabbing the latest image from the database and then on success it replace the current photo and show it? What about the adressbar, in facebook the adressbar changes align with loading new photo.
Any well explained answer for procedure of making this, will accept the answer
This here will load images from the database using ajax (next/previous). Also includes guides and a preloader (hosted here http://www.preloaders.net/). Let me know if you have any questions.
Here you go. these are 3 files
index.php ...display page
ajax.php ...read database for images
show.php ...loads images
just remember to set host, user, password & databasename in ajax.php
copy & paste these:
1. index.php
<?php
include("ajax.php");
?>
<script type="text/javascript" src="JQUERY/jquery.js"></script>
<script>
var ID = "<?php echo $id; ?>";
var inc = ID + 1;
var dec = ID;
var totalpages = "<?php echo $totalpages + 1; ?>";
$(function(){
$('.loader').hide();
<!-- np = next & prev button functions -->
$('.np').click(function() {
if($(this).attr('id') == "next") {
$(this).attr('push', inc++);
if($(this).attr('push')<totalpages) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
dec = inc - 2;
$('#images').hide();
}
}
else if($(this).attr('id') == "prev") {
$(this).attr('push', dec--);
if($(this).attr('push')>-1) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
inc = dec + 2;
$('#images').hide();
}
}
});
});
<!-- this function is called after ajax send its request -->
function AjaxFunc(return_value) {
$('#images').html(return_value);
$('.loader').hide();
$('#images').show();
}
</script>
<div id="images">
<!-- loads default numbers of images. whats inside here will change once you click next or prev -->
<?php
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
</div>
<!-- next & previous buttons -->
<a class="np" id="prev" push="<?php echo $id; ?>" href="#">Prev</a>
<a class="np" id="next" push="<?php echo $id + 1; ?>" href="#">Next</a>
<!-- preloader. hidden on start. will show while images load -->
<img class="loader" src="http://www.preloaders.net/generator.php?image=75&speed=5&fore_color=000000&back_color=FFFFFF&size=64x64&transparency=0&reverse=0&orig_colors=0&uncacher=26.066433149389923"/>
2. ajax.php
<?php
//id is tjhe page number. it is 0 by default. while clicking next/prev, this will not change. set it like this: file?id=0
$id = $_GET['id'];
//connect to the databsae
$host="localhost";
$user = "username";
$password = "";
$database = "database_name";
$connect = mysql_connect($host, $user, $password) or die("MySQL Connection Failed");
mysql_select_db($database) or die ("Database Connection Fail");
//set your the limit of images to be displayed
$limit = 5;
//push images into array
$q = mysql_query("SELECT * FROM image_table");
$num = mysql_num_rows($q);
while($r = mysql_fetch_array($q)) {
$imagearray[] = "<img src='"
.$r['IMAGE_URL']
."'/>";
}
//will determine total number of pages based on the limit you set
$totalpages = ceil($num/$limit) - 1;
?>
3. show.php
<?php
include("ajax.php");
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
If you are sorting your photos by date DESC and you got the current photos date do the following:
To find the next photo: Order your photos by date DESC and select the first photo whos date is smaller than the date of the current photo. Fetch only the first one.
To find the prev photo: Order your photos by date ASC and select the first photo whos date is greater than the date of the current photo. Fetch only the first one.
Construct the SQL-Statements for this by yourself.
Related
I have a main.php page where I have a while loop that displays the first 10 items from the database. I want to load the next 10 items once a load more button is clicked.
$res = mysql_query("SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 10");
if($res && mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$id = $row['id'];
?>
<div class="main_page">
item id <?php echo $id; ?>
</div>
<button class="load_more">Load More</button>
....
What is a good way of doing this? Any help is much appreciated!
UPDATE:
right now i have this script for the load more button:
<script type="text/javascript">
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?id=" + $(".ad_display:last").attr("id"),
success: function(html){
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
after the form of the filters is submitted, the url looks somewhat like this:
index.php?search=&category=0&ad_order=1
how do I pass on the search (even if empty), ad_order, and category value to the loadmore.php?
limit 0, 10 will display the first 10 items from your query. limit 20,10 will display 10 items starting with the 20th item (counting from zero). You can pass the page number or the number of items retrieved up to now in a parameter when you call the page that does the query. This will involve either reloading the current page with a different start index in limit, or issuing an ajax query that lets you load more items without reloading the page.
Apart from the answer posted by Octern, not sure what you want to achieve for your second question but try:
<script type="text/javascript">
//saving the GET variables
ad = <?php echo $_GET['ad_order']; ?>
catg = <?php echo $_GET['category']; ?>
search = <?php echo $_GET['search']; ?>
//default value of record to start from
rec = 0;
$(document).ready(function(){
$(".load_more").click(function (){
$('.load_more').html('<img src="images/ajax-loader.gif" />');
$.ajax({
//passing them here
//URL updated to pass rec
url: "loadmore.php?id=" + $(".ad_display:last").attr("id")+"&search="+search+"&category="+catg+"&ad_order="+ad+"&rec="+rec,
success: function(html){
//updating counter to start from record
rec += 10;
if(html){
$(".main_page").append(html);
$('.load_more').html('Load More');
}else{
$('.load_more').replaceWith('No posts');
}
}
});
});
});
</script>
In your loadmore.php you need to relevant code to fetch the above $_GET values
Your query will be something like:
$res = mysql_query("SELECT * FROM classifieds WHERE date < '".mysql_real_escape_string($_GET['id'])."' AND search = '".$_GET['search']."' AND category = '".$_GET['category']."' AND ad_order = '".$_GET['ad_order']."' ORDER BY date DESC LIMIT '".$_GET['rec']."',10");
So everytime you click on the load_more, the limit will change as LIMIT 0,10 -> LIMIT 10,10 -> LIMIT 20,10 etc.
I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:
Show Posts
<div id="result"></div>
jQuery Part:
function ShowPost(){
$.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
function(data) {
$("#result").html(data);
});
};
PHP Part:
if ($_POST['action'] == "showpost") {
$db->query( "SELECT title FROM post LIMIT 0,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...
i hope you understand my question.
Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:
jQuery Part:
var pageNumber = 0;
function ShowPost() {
pageNumber++;
$.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
function(data) {
$("#result").html(data);
});
};
Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.
PHP Part:
if ($_POST['action'] == "showpost") {
var pageSize = 5;
var pageNumber = $_POST['pageNumber'];
var from = (pageNumber - 1) * pageSize;
var to = pageNumber * pageSize;
$db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);
while ( $row = $db->get_row()) { echo $row['title']."<br>"; }
}
Just implement the pagination limit in ur query
var offset = -5;
function ShowPost(){
offset = offset + 5;
$.post(dir + 'engine/ajax/posts.php', {action:"showpost",offset:offset},
function(data) {
$("#result").html(data);
});
};
PHP part
if ($_POST['action'] == "showpost") {
$vOffset = $_POST['offset'];
$db->query( "SELECT title FROM post LIMIT $vOffset,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Take a hidden field in html and update it's value after every success call and when next time you call for next record send that value in post.
<input type="hidden" name="limit" value="5">
Show Posts
<div id="result"></div>
Hello i have gone through Long polling, websockets and APE, Ajax push, Ajax Pull. As the technology of websockets isnt yet much introduced in our World Wide Web now. i thought i would use the normal setInterval functions to check the database. this is for a chat application, my code :-
on Home.php :
Javascript:
$(document).ready(function(){
setInterval(function(){
var id = $id; // this is the id of the last message inserted in the database
var data = 'id='+id;
$.ajax({
type : "POST",
url : "check.php",
data : data,
success : function(data){
if(data)
{
$(".comments").append(data);
}
}
});
},1000);
and check.php
php code :
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM messages WHERE id>'$id' ORDER BY id DESC");
$num2 = mysql_num_rows($get);
$get2 = mysql_fetch_assoc($get);
$id = $get2['id'];
if($num2!=0)
{
$username = $get2['username'];
$a = mysql_query("SELECT * FROM people WHERE username='$username'");
$n = mysql_num_rows($a);
$b = mysql_fetch_assoc($a);
$file = $b['filename'];
$pic = "<img src=\"images/" .$file. "\" width=\"40\" height=\"40\">";
$name = $get2['fullname'];
$message = $get2['message'];
echo $pic.$message."<br/>";
}
else
{
}
if there is a new record inserted in the database it echo's out properly but then it doesnt update the $id in the home.php page so it sends the old id again and again and the comment gets appended again and again.
what i want is. for every interval . the $id of the home.php should be updated so that it sends only the present message id to the check.php page.
I gues that the first code you've post is in your template of home.php and the $id then goes replaced with the real number of the last ID.
this works for the first time when the page is processed with PHP, but once downloaded on users machine, you only have to rely on JavaScript...
I'm not sure in which form you receive the data from check.php, but you need to do something like
id = data.id
data = 'id='+id;
Is there a way to count how many times an image how been clicked. And once the image is clicked have it displayed?
I am currently pulling random images from a database and want to show which is has been clicked the most.
<html> <body>
<div style="float:left"> <?php // Connect to the database mysql_connect ('localhost', 'root') ; mysql_select_db ('links');
// Number of images $num_displayed = 1 ;
// Select random images from the database $result = mysql_query ("SELECT * FROM links ORDER BY RAND() LIMIT $num_displayed");
// For all the rows that are selected while ($row = mysql_fetch_array($result))
// Display images { echo "<img src=\"".$row["image"]."\" border=0 alt=\"".$row["text"]."\">"; } ?> </div>
<div style="float:left; margin-left:100px"> <?php include("image2.php"); ?>
</div> </body> </html>
thanks.
Create a trigger in image table to count selects
CREATE TRIGGER `database_name`.`trigger_name` BEFORE SELECT INSERT ON
`database_name`.`images_table_name` FOR EACH ROW
BEGIN
UPDATE
`database_name`.`images_table_name`
SET
`database_name`.`images_table_name`.`counter` = `database_name`.`images_table_name`.`counter` + 1
WHERE
`database_name`.`images_table_name`.`id` = NEW.`id`;
END$$
Perform your querys ordering by counter field.
To register clicks, implements a click tracker quering an update on second field, like 'clicks'
You can do this using javascript:
In head tag:
<script type="text/javascript">
var count = 0;
function changevar(){
count = count + 1;
if (count == 3) {
alert('Done');
}
}
</script>
In body tag:
<img src="image.png" onClick="changevar()"/>
How about counting each time the image is displayed? This is an option if and only if there are no other images which can be to it in the way an image album viewer works.
Use php to render the image, and run a small script in there which increments the number of times this image has been clicked (or displayed). Alternatively you could create an entry for each time the image is displayed saving lots more possibly interesting information such as image, last_view, ip, count and or referrer (if it works;untested). Recording the IP would allow you to keep track of unique views with count showing you how many times they reviewed the image; this depends on how you implement it.
$name = trim($_GET['img']);
if (!isset($_GET['img'] || empty($name)) {
// Check url var wasn't omitted or typed incorrectly.
die("Image not specified.");
}
// This is just an example path. It would be a good idea to specify a path
// like this to ensure that people don't try and use it to display files
// that you wouldn't want them too.
//eg. images you don't want to keep records of.
$image = "/images/$name";
$date = time();
$ip = $_SERVER['REMOTE_ADDR'];
$ref = $_SERVER['HTTP_REFERER'];
if (!file_exists($image)) {
// Ensure that something exists at $image
die("Invalid image.");
}
$f = fopen($image, 'r');
if (!$f) {
// Make sure that the contents of the file can be opened.
die("Unable to open image.");
}
$info = #imagegetsize($image);
if (!$info) {
// This is to make sure that the $image contains a path
// to an image not just a regular file.
die("Invalid image type.");
}
Header("Content-type: {$info['mime']}");
echo fread($f, filesize($image));
fclose($f);
/****************
* Script for saving image 'click' information.
***************/
exit;
Display the image like this
<img src="/image.php?img=example.png" />
If you are having troubles and images are displaying correctly, open the path in your browser to see the errors.
I'm making a rating system, and I have the following jQuery code on my index.php page:
<script type="text/javascript">
$(document).ready(function() {
$("[id^=rating_]").hover(function() {
var rid = $(this).attr("id").split("_")[1];
$("#rating_"+rid).children("[class^=star_]").children('img').hover(function() {
$("#rating_"+rid).children("[class^=star_]").children('img').removeClass("hover");
/* The hovered item number */
var hovered = $(this).parent().attr("class").split("_")[1];
var hovered2 = $(this).parent().attr("class").split("_")[1];
while(hovered > 0) {
$("#rating_"+rid).children(".star_"+hovered).children('img').addClass("hover");
hovered--;
}
$("#rating_"+rid).children("[class^=star_]").click(function() {
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
});
});
});
</script>
Basically theres a hover effect and then when you click on the star, it'll send a post request to send.php, with the info on the rating clicked and the id of the element. Below this script I have some PHP that looks like this:
<?php
$query = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($query)) {
$rating = (int)$row[rating];
?>
<div id="rating_<?php echo $row[id]; ?>">
<span class="star_1"><img src="star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span>
<span class="star_2"><img src="star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span>
<span class="star_3"><img src="star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span>
<span class="star_4"><img src="star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span>
<span class="star_5"><img src="star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span>
<div class="clearleft"> </div>
</div>
<br />
<?php
}
?>
And then of course I have some CSS to make it look nice.
The send.php file looks like this:
<?php
mysql_connect("localhost", "admin", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$rating = (int)$_POST['rating'];
$id = (int)$_POST['rid'];
$query = mysql_query("SELECT * FROM test WHERE id = '".$id."'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
if($rating > 5 || $rating < 1) {
echo"Rating can't be below 1 or more than 5";
}
else {
$total_ratings = $row['total_ratings'];
$total_rating = $row['total_rating'];
$current_rating = $row['rating'];
$new_total_rating = $total_rating + $rating;
$new_total_ratings = $total_ratings + 1;
$new_rating = $new_total_rating / $new_total_ratings;
// Lets run the queries.
mysql_query("UPDATE test SET total_rating = '".$new_total_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET rating = '".$new_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET total_ratings = '".$new_total_ratings."' WHERE id = '".$id."'") or die(mysql_error());
}
}
?>
There are 3 rating columns in the database table;
total_rating: total ratings (all the ratings added together).
rating: the current rating
total_ratings: the amount of ratings.
The problem is, if I change the $_POST['rating'] and $_POST['rid'] to $_GET and put the information int he url, for instance, send.php?id=1&rating=4, it works, and the database gets updated. However, when I press the stars, the database isn't updated. After messing around with the script I realised that the post must be working, however the id returns as 0.
To test this further I put this in the click function:
document.write(current_star+rid);
To see what was returned. The problem seems to be that the number that is returned is multiplied by the amount of times I hover over elements. So if I hover over maybe, 6 of the stars, then the current_star and ID will be repeated 6 times.
I feel like I'm so close to getting this to work, has anyone got any idea what's up with it? Thanks in advance.
And important thing to realize about jQuery's event handling is that it is registry-based, meaning that jQuery allows you to register multiple callbacks for any particular event, and it will invoke them in the order in which they were bound.
The reason you're seeing repeated current_star and id values is because you keep binding more and more events on every hover. This is because have your click() call inside your hover() call, therefore every time you hover, you will bind another click() event.
Try binding your click() event outside your hover event, using something like this:
$("[id^=rating_]").children("[class^=star_]").click(function() {
var rid = $(this).parent().attr("id").split("_")[1];
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
You also probably don't want to bind one hover() call inside the other, for the same reason.
I noticed you have used $_POST['rid'] instead of $_POST['id']. May be that's your problem.