How do i use Javascript to "store" and "call" data? - php

I'm making a "Catalog" page for a fake shop site, when i click one of the thumbnails shown on the page a java-script overlay is meant to show up with all the information for the product (such as a larger image 'photo1') with that thumbnail (The products are in an SQL database).
While this does pull up an overlay as intended it doesn't get just the one related 'photo1', it instead gets all of them from the table.
I've had help from a teacher but she couldn't even help, but from what i gather i need a way to store what thumbnail was chosen so i can clarify what info to pull for the overlay.
Main:
<div id="overlay">
<div>
<?php
include 'includes/connection.php';
try {
$sql = 'SELECT * FROM item;';
$resultSet = $pdo->query($sql);
} // end try
catch (PDOException $e) {
echo 'Error fetching items: ' . $e->getMessage();
exit();
} // end catch
foreach ($resultSet as $row) {
// put each rows's elements into variables
$itemName = $row['itemName'];
$unitPrice = $row['unitPrice'];
$qtyOnHand = $row['qtyOnHand'];
$thumbNail = $row['thumbNail'];
$photo1 = $row['photo1'];
echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" ></td>';
}
?>
<p>Content you want the user to see goes here.</p>
Click here to [<a href='#' onclick='overlay()'>close</a>]
</div>
</div>
<div id="MainHolder">
<div id="Headerbar">
<?php
include 'includes/login.php';
?>
<div class="ContentBody">
<div class="Content">
<article>
<h2>Store</h2>
<?php
include 'includes/connection.php';
try
{
$sql = 'SELECT * FROM item;';
$resultSet = $pdo->query($sql);
} // end try
catch (PDOException $e)
{
echo 'Error fetching items: ' . $e->getMessage();
exit();
} // end catch
?>
<!-- open table -->
<article>
<?php
// read result set and populate table
foreach ($resultSet as $row)
{
// put each rows's elements into variables
$itemName = $row['itemName'];
$thumbNail = $row['thumbNail'];
$qtyOnHand = $row['qtyOnHand'];
// test for out of stock condition
// if no stock, display out of stock image else display add to cart image
if ($qtyOnHand <= 0) {
echo '<td><img src="images/outOfStock.png" border="3" class="floatingImage" height="80" width="80" alt="" title=""></td>';
} else {
echo '<td><img class="floatingImage" border="3" src="' .$thumbNail .'" width="80" height="80" alt="' .$itemName .'" title="' .$itemName .'" onclick="overlay()" ></td>';
}
} // end foreach
// close table
echo '</article>';
?>
</article>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
</div>
</div>
Javascript:
function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
The overlay and catalog are in the same file.
I'm still learning, so my apologies for any messy formatting/code.
EDIT: I've merged some of the code, this shows pretty much my whole store page other than Headers, ect...

You need to edit your overlay function to send the itemName to server, this will tell your server which item the user clicked on.
overlay function:
function overlay() {
var item = this.getAttribute("title");//this gets the name of item that was clicked
}
Now we need to set up an ajax request to the server.
function ajaxRequest(item) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){//show the overlay after we recieve a response from the server
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
el.innerHtml = ''; //remove previous response
el.innerHTML=xmlhttp.responseText; //insert the response in your overlay
}
}
xmlhttp.open("GET","overlay.php?item="+ encodeURIComponent(item),true);
xmlhttp.send();
}
}
Now we need to edit the overlay function to make a call to the ajaxRequest function:
function overlay() {
var item = this.getAttribute("title");//this gets the name of item that was clicked
ajaxRequest(item); //send the item name to server
}
After doing this, your PHP will receive a the variable on your server. Create a new file called overlay.php and insert the following code. Save this file in the same directory as your Store.php file.
overlay.php:
<?php
if (isset($_GET['item'])) {//check if you received the name
$itemName = $_GET['item'];
//query database for the itemName
try
{
$sql = 'SELECT * FROM item WHERE itemName ='.$itemName.';';//just select data with the matching item name.
$resultSet = $pdo->query($sql);
} // end try
catch (PDOException $e)
{
echo 'Error fetching items: ' . $e->getMessage();
exit();
} // end catch
//fetch the data
foreach ($resultSet as $row) {
// put each rows's elements into variables
$itemName = $row['itemName'];
$unitPrice = $row['unitPrice'];
$qtyOnHand = $row['qtyOnHand'];
$thumbNail = $row['thumbNail'];
$photo1 = $row['photo1'];
echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" ></td>';
}//end foreach
}//end if
?>

When you first get the Product from the DB using this loop:
foreach ($resultSet as $row) {
// put each rows's elements into variables
$itemName = $row['itemName'];
$unitPrice = $row['unitPrice'];
$qtyOnHand = $row['qtyOnHand'];
$thumbNail = $row['thumbNail'];
$photo1 = $row['photo1'];
echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" ></td>';
}
Are those all the attributes that you want to show when the User clicks on the image for the overlay? If so, just store the values in the actual <img> tag:
echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" data-unit-price="$unitPrice" data-qty="$qtyOnhand"></td>';
Then you can use Javascript to access the data and show in your overlay.

I try to understand your problem and used jQuery to solve it.
First you have to load jQuery lib
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
And add display:none style to every production info in overlay(default is hidden).
echo '<td><img src="' .$photo1 .'" width="500" height="500" alt="$itemName" title="$itemName" style="display:none" ></td>';
Remove thumbnail inline onClick event trigger
echo '<td><img class="floatingImage" border="3" src="' .$thumbNail .'" width="80" height="80" alt="' .$itemName .'" title="' .$itemName.'"'></td>';
Add this click event handler thus jQuery can show the production info which user clicked.
$(".floatingImage").click(function(){
var itemName = $(this).attr('alt');
$('#overlay img').hide();
$('#overlay img[alt="'+itemName+'"]').show();
overlay();
});
Hope this is helpful for you.

If you want to store data absolutely on the client side, you can use local storage feature of html5 with embedded sql lite database to store and retrieve information using Javascript.

Related

php echo iframe or image

Hey everyone I am having an issue with echoing an image or an iframe, the idea is there is an image link or an iframe in the same row in the database & i want to only echo what the string content is, if it echos the iframe there is a blank space of an image & underneath is the youtube video, if it echos the image the iframe does not show, they both currently echo the same row id labled url, I only want one to echo based on the string content instead of both echo's.
Here is the code I use to fetch the stuff, its only the echo area you want to pay attention to, I am not sure what kind of, if or else statement i could put in here.
< ?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 4;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM bookmarks WHERE 1 ORDER BY id DESC LIMIT $limit OFFSET
$offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
echo '<img src=' . $row['url'] . '></br>'; /*here */
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
} }
?>
This script is a get results php
The best solution would be to save the data in different columns in the database. But if you want to keep the current structure would be able to check if the string contains HTML, then it is an iframe. Otherwise it is a link to the image.
<?php
if($row['url'] == strip_tags($row['url'])) {
//No HTML in string = link
echo '<img src="' . $row['url'] . '" alt="" />';
} else {
//Contains HTML = iframe
echo $row['url'];
}
?>
This assumes that you in your database have saved the values as either http://www.exempel.com or <iframe src =" http: // www ... ">. If the iframe-value also consists only of a URL, you must use another solution.
If you know whether the url is an image or video when you save them in the database then you could add another field for the media type. You could then use this in an if statement in your code, for example:
if (count($results) > 0) {
foreach ($results as $row) {
echo '<li><kef>' . $row['title'] . '</kef></br>';
if ($row['mediaType'] === 'image') {
echo '<img src=' . $row['url'] . '></br>'; /*here */
} if ($row['mediaType'] === 'video') {
echo '<kef1>' . $row['url'] . '</kef1></br>'; /*and here*/
}
echo '<kef2>' . $row['desc'] . '</kef2></br>';
echo '<kef3>' . $row['tag'] . '</kef3></br> </br> </li>';
}
}

PHP MySQL Database Images Toggler

I have built a little uploader that works fine, uploading the images file path to my DB, and storing the image in a folder.
Now I also have made a call that will call only images with the same ID as the Property ID it has assigned.
Where I have trouble is the Image display, I am looking for a simple way to toggle between the images in the database, but even before that, I need to know why the Database call only displays one of the images stored in the DB.
Here is my code so far :
PHP
if ($id) {
$query = "SELECT houses.*, gallery_photos.* " .
"FROM houses LEFT JOIN gallery_photos " .
"ON $id = gallery_photos.photo_category";
$result = mysql_query($query) or die(mysql_error());
}
// Print out the contents of each row into a table
while ($row = mysql_fetch_array($result)) {
$images_dir = "houses";
$photo_caption = $row['photo_caption'];
$photo_filename = $row['photo_filename'];
$photo_id = $row['photo_id'];
}
and the display happens withing a larger ECHO command, I will add a little of it so you get the idea :
Within the ECHO
echo "
<li>
<div id='imagizer'> <img src='" . $images_dir . "/" . $photo_filename ."?id=" . $photo_id . " ' title='$photo_caption'/></div>
</li>
There are many more elements within the li element that work fine, like Title, Price, Summary, etc etc.... But I can simply not accomplish 3 thing here :
Getting all the images to display (I only get one, which would be fine if the toggler worked).
Making a toggler to display the next image that has the same category_id.
Optional (An image slider)
UPDATE
This is kind of working, but I get various duplicate entries! It seems that for every picture I get 1 entry on the list. So if 4 pics, 4 entries, if 2, only 2 entries.
function showShort() {
$houses = #mysql_query('SELECT houses.*, gallery_photos.*
FROM houses LEFT JOIN gallery_photos
ON houses.id = gallery_photos.photo_category');
if (!$houses) {
die('<p> Error retrieving Propertys from database!<br />' . 'Error: ' . mysql_error() . '</p>');
}
while ($house = mysql_fetch_array($houses)) {
$id = $house['id'];
$title = htmlspecialchars($house['title']);
$ref = $house['ref'];
$summary = htmlspecialchars($house['summary']);
// $content = $house['content'];
$price = $house['price'];
$houseorder = $house['houseorder'];
$pool = $house['pool'];
$bedrooms = $house['bedrooms'];
$bathrooms = $house['bathrooms'];
$aircon = $house['aircon'];
$basement = $house['basement'];
$location = $house['location'];
$floorm = $house['floorm'];
$aream = $house['aream'];
$garage = $house['garage'];
$furbished = $house['furbished'];
$images_dir = "houses";
$photo_caption = $house['photo_caption'];
$photo_filename = $house['photo_filename'];
$photo_category = $house['photo_category'];
$photo_id = $house['photo_id'];
if ($garage == 'Yes') {
($garage = "Garage : Yes<br>");
} elseif ($garage == 'No') {
($garage = "");
}
if ($pool == 'Yes') {
($pool = "Swimming Pool : Yes<br>");
} elseif ($pool == 'No') {
($pool = "");
}
if ($aircon == 'Yes') {
($aircon = "Air Condition : Yes<br>");
} elseif ($aircon == 'No') {
($aircon = "");
}
if ($basement == 'Yes') {
($basement = "Basement : Yes<br>");
} elseif ($basement == 'No') {
($basement = "");
}
if ($furbished == 'Yes') {
($furbished = "Furbished : Yes<br>");
} elseif ($furbished == 'No') {
($furbished = "");
}
echo "
<li>
<div id='summarybox'>
<div id='titlestyle'> $title </div><br>
<div id='imagebox'> </div>
<div id='refstyle'> Ref. $ref </div>
<div id='details1'>
Bedrooms : $bedrooms <br>
Bathrooms: $bathrooms <br>
Living Area : $floorm m² <br>
Plot Area : $aream m² <br>
Location : $location <br>
</div>
<div id='details2'>
$pool
$aircon
$basement
$furbished
$garage </div>
<section class='ac-container'>
<div>
<input id='$id' name='accordion-1' type='checkbox' />
<label for='$id' >Read More</label>
<article class='ac-small'>
<div id='summarystyle'> $summary </div>
<div id='price'>Price : $price </div><br>
<div id='imagizer' align='center'>
<ul id='$id'>
<li><a href='" . $images_dir . "/" . $photo_filename . "' rel='lightbox[$photo_category]' title='$photo_caption'><img src='" . $images_dir . "/" . $photo_filename . "' height='50%' with='50%'/></a></li>
</ul>
</article>
</div>
</selection>
<br>
<div id='admbuttons'><a href='editProperty.php?id=$id' ><button>Edit</button></a>
<a href='deleteProperty.php?id=$id' onclick='return confirm()'> <button>Delete</button></a></div>
</div>
</li>";
}
}
This is the live example where i have used this idea just open the below link and click on the thumb image and then slide inside the lightbox.
Inspect the image with firebug and see the anchor tags below the image you will get the logic what i am trying to say and then you can manage it into your code
http://dev.tasolglobal.com/osclass/
your echo statement should be like in for loop
while ($row = mysql_fetch_array($result)) {
$images_dir = "houses";
$photo_caption = $row['photo_caption'];
$photo_filename = $row['photo_filename'];
$photo_id = $row['photo_id'];
echo "
<li>
<div id='imagizer'> <img src='" . $images_dir . "/" . $photo_filename ."' id=" . $photo_id . " title='$photo_caption'/></div>
</li>
}
id and src should have some space to print in echo.
please add above code in you for loop sure it will work for you.
The main thumb single image
<a href="url of the first image" rel="lightbox['unique name for a particular bunch of image']><img src="url of the first image" /></a>
Just fire a query and get all the image url only for the particular category and run a loop for the urls to create anchor tags with rel
for($b=1;$b<$thumb_url;$b++)
{
echo = '';
}
These image url are in the href so will not load on page load and when the lightbox will be triggered on the click of the first image it will load all the images with a particular unique string in the rel="lightbox[]" and will show next and previous link to show images like slider
You can use "cat_" then the unique id of a particular category to make unique the rel of those particular images.
I have tried it and it works
UPDATE
What you need to do is do not loop the li but just place the first image in the li inside the img tag and the unique rel and then after the li you have to run the loop for the rest of the category images and create anchor tag with image url in the href and rel similar to the first image
Do not forget to include the js and css for the light box
<div id='imagizer' align='center'>
<ul id='$id'>
<li><a href='" . $images_dir . "/" . $photo_filename . "' rel='lightbox[$photo_category]' title='$photo_caption'><img src='" . $images_dir . "/" . $photo_filename . "' height='50%' with='50%'/></a></li>
</ul>
//Put your loop here to make the anchor tags and keep the url in the href only with the rel corresponding to the first image so they will be treated as a bunch by lightbox
Create a common select function and try query with it and then use for loop on the result associative array it will be less confusion and neat code
Execute Select Query
function select ($sql="", $fetch = "mysql_fetch_assoc")
{
global $conn;
$results = #mysql_query($sql,$conn);
if(!$results) {
echo mysql_errno()." : ". mysql_error();
}
$data = array();
while ($row = $fetch($results))
{
$data[] = $row;
}
mysql_free_result($results);
return $data;
}

onclick confirm function with different text from array

I am having an issue with attempting to show different confirm text from an array when using a hyperlink. The text always ends up being from the last confirmation text in the array. I have seen 2 examples on this forum using a function() in a function but I was not able to get this working from viewing the examples.
Here is my code:
echo '
<script type="text/javascript">
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<script type="text/javascript">
var item_detail = ', json_encode($item['reported_spam']['detail']),'
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
</script>
<a id="mylink[]" onclick="getDetails(item_detail);" href="'.$link.'" style="text-decoration:none;">
<img id="myImage" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thanks.
Edit: I figured it out.
#Grant Zhu: Arrays are not written like that in php and one can progress to the next key just using the empty square brackets. You were correct as I did make an err for the image id array and the js variables. Also for php when using single quotes inside echo with single quotes one must use the backslash (unless using php again).
I got it working as such:
echo '
<script type="text/javascript">
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php?report='. $item['id'];
echo '
<a id="mylink[]" onclick="getDetails(\'',$item['reported_spam']['detail'],'\');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage[]" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thank you.
$link = 'http://test_url/mytest.php;report='. $item['id'];
this code is weird , I think your code might be
$link = 'http://test_url/mytest.php?report='. $item['id'];
You should check the javascript generated and you will find there're multiple declarations of item_detail and item_NoLink. That means you assign the values to the same variables again and again. Of course, the last assignment takes effect in the end.
You can put the detail text directly in the getDetails function. Make sure the text is quoted by '. And you'd better make the id of <a> and <img> unique because that's what id means. I'm not familiar with PHP, check the syntax below if it's correct.
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<a id="mylink$item['id']" onclick="getDetails(', json_encode($item['reported_spam']['detail']),');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage$item['id']" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}

Ajax request and jquery conflict

I have gallery.php that loads images with src path from a database.
I also have an external main.js that detects a click on a .thumbnail.
Everything works flawlessly until I load different images (another category of images, another set) via ajax. (the load() function of jquery) Everything shows just fine, but a problem with javascript appears.
After that, I can't retrieve the src attribute of my thumbnail. Here's what I mean.
BEFORE AJAX
Category 1 pictures/thumbnails
<a class="thumbnail"><img src="ressources/images/image1Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image2Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image3Small.jpg" /></a>';
And so on...
AFTER AJAX CALL
Category 2 pictures/thumbnails
<a class="thumbnail"><img src="ressources/images/image4Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image5Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image6Small.jpg" /></a>';
As you can see, everything is like before. The a tag has the same class as the old est of pictures. But when I call the function containing :
var path = $(this).children().attr("src");
It now returns : undefined instead of ressources/images/imageXSmall.jpg
I tried checking if $(this) returned something else after, but no success.
I was wondering if when an external .php file was loaded via jquery.load(), the link between those newly created <a class="thumbnail"> tags and main.js were lost. Like if I had to reload main.js after the jquery.load() function. Or something like that...
Thank you!
EDIT Here's the code:
When clicking on a link to different
category
.linkSubCat being different categories
$(".linkSubCat").click(function(){loadImages($(this).attr("id"));});
then
function loadImages(pCategory) {
switch (pCategory) {
case "subCat00":
$(".pics").load('loadImages.php',{category:0});
break;
case "subCat01":
$(".pics").load('loadImages.php',{category:1});
break;
case "subCat02":
$(".pics").load('loadImages.php',{category:2});
break;
case "subCat03":
$(".pics").load('loadImages.php',{category:3});
break;
default:
$(".pics").load('loadImages.php',{category:0});
break;
}
}
loadImages.php
<?php
$connection = mysql_connect("localhost","root", "") or die("Error Connecting : " . mysql_error());
if (!mysql_select_db("taktak")) die('Error connecting to database : ' . mysql_error());
function createThumbPHP() {
if(isset($_POST['category'])) {
if($_POST['category'] == 0){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 1){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 1");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 2){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 2");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 3){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 3");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}
return $thumbHtml;
}
else {
$errorMSG = "Error Loading Images";
return $errorMSG;
}
}
echo createThumbPHP();
?>
So everything does what it's supposed to do. Here'sthe problem. This javascript code in main.js :
$(".thumbnail").click(
function(){
$('#imageBig img').remove();
var path = $(this).children().attr("src");
var newPath = path.substring(0, path.length-9);
var newPath2 = newPath += ".jpg";
var imageLoad = new Image();
$(imageLoad).load(function () {
if (--imageLoad == 0) {
// ALL DONE!
}
// anything in this function will execute after the image loads
$('#loader').hide();
var newImg = $('<img />').attr('src',$(this).attr('src'));
$('#imageBig').append( $(newImg) ); // I assume this is the code you wanted to execute
})
.attr('src',newPath2);
}
)
It removes the img in #imageBig, but doesn't seem to get the path of $(this).children().attr("src"); This script worked perfectly before I loaded different thumbnails (even with the same setup (classes, order, ...))
Try using the jQuery "live" event binding, eg
instead of this
$(".thumbnail").click(
use this
$('.thumbnail').live('click',
When using the regular event binders (eg $.click()), the handler is only bound to those elements matched at the time of the call. When you load new elements via AJAX, these will not be bound.
From the jQuery manual
Attach a handler to the event for all elements which match the current selector, now and in the future.

on click change questions displayed

I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.

Categories