Ajax request and jquery conflict - php

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.

Related

Ajax Div Refreshing Too Fast

I have a form that posts to a script via ajax, the script inserts the form data into a database and using ajax i the refresh the div on the original page which then shows the form as well as a list of records in the database (from the form input)
I hope that makes sense.
My issue is that sometimes, maybe 1 time in 20, the div refreshes too quickly and doesn't pick up on the new data if i refresh the page its there and if i submit a new record both records are then in the list.
I guess i just need to delay the refreshing but i don't know how.
thanks,
php
echo '<div id="cuttingListDiv">';
$sql = "SELECT * FROM `cuttingList` WHERE jobRef = '".$_SESSION["jobRef"]."' ORDER BY pieceMaterialName, pieceThickness ASC";
$results = $dbconn->query($sql);
if ($results->num_rows > 0) {
echo '<h3>Cutting List:</h3>';
echo '<div align="center">';
while($row = $results->fetch_assoc()) {
echo '<br />';
echo '<div class="row">';
echo '<div class="col" align="center">';
echo '<h5>'.$row["pieceMaterialName"] . ' - ' . $row["pieceLength"] . ' x&nbsp' . $row["pieceWidth"] . ' x&nbsp' . $row["pieceThickness"] . 'mm</h5>';
echo '<br />';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
echo '</div>';
ajax script
session_start();
include '_script_sqlConnection.php';
$pieceLength = strip_tags($_POST['pieceLength']);
$pieceWidth = strip_tags($_POST['pieceWidth']);
$thickness = strip_tags($_POST['thickness']);
$material = strip_tags($_POST['material']);
$materialName = strip_tags($_POST['materialName']);
$sheetID = strip_tags($_POST['sheetID']);
// Swap width & length id width bigger
if ($pieceWidth > $pieceLength) {
$tmpDimm = $pieceLength;
$pieceLength = $pieceWidth;
$pieceWidth = $tmpDimm;
}
$sql = "INSERT INTO `cuttingList`(`orderRef`, `pieceMaterialName`, `pieceThickness`, `pieceLength`, `pieceWidth`, `sheetID`, `pieceWeight`, `qty`) VALUES ('".$_SESSION["quoteRef"]."', '".$materialName."', '".$thickness."', '".$pieceLength."', '".$pieceWidth."', '".$sheetID."', '".$pieceWeight."', '1')";
if ($dbconn->query($sql) === FALSE) {
echo "Error Adding Pieces To Cut List.<br />";
}
javascript
$("#cuttingListForm").submit(function(){
$.ajax({
type: "POST",
url: "_script_ajax_addToCuttingList.php",
data: $('form.cuttingListForm').serialize(),
success: function() {
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}
});
});
Use the JS function setTimeout
// example of usage for setTimeout:
setTimeout( function(){
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}, 2000 );
In the example you have 2000 milliseconds for 2 second wait before fired the call.
Thanks for you help but i went a different way as i was still having trouble with both of these methods.
At the very top of the div that refreshes I used the php sleep command to wait 1 second, now it works perfectly.
Thanks,

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;
}

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

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.

Get "ActivityID" from a PHP file and put it in a JS script.

I'm making a travelguide. I'm displaying data(activity) from a database(mysql). Each activity has his own button. When you push this button you add that specific activity to your travelguide. This all works, but i must refresh the page to display the activities that are added to the guide. Now i have made a working javascript script, but it's not dynamic.
function MakeRequest()
{
var test = 1;
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "get_test.php?q="+test, true);
xmlHttp.send(null);
}
You see de variable: "var test = 1;"
The number 1 stands for the ActivityID 1. So now if you push the button it shows the activity with the ActivityID = 1. If i change the number to 2, is shows the activity with the ActivityID = 2.
I want to change the variable: "var test = 1;" The number must automaticly be inserted, it must be the same number as the ActivityID of the activity where is push the button.
<?php
$sql = "SELECT * FROM activity";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC))
{
echo '<div id="activity'.$row['ActivityID'].'">';
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['ActivityIMG'] ) . '" >', '<br>';
//echo $row['Activityname'], '<br>';
//echo $row['Activitydescription'];
echo '<input type="button" class="addActivity" onclick="MakeRequest();" value="Activiteit toevoegen" data-activity="' . $row['ActivityID'] . '">';
echo '</div>';
}
?>
This is the php file:"get_activity". This is the code that displays the data en display the button. This button gets automaticly the ActivityID from the specific activity. This way i only need one script for all the activities. I want to do the same with the javascript, but i don't know how?
If I understand you want to give var test the correct id depending on the button you press.
Why don't you just pass a parameter to your js function?
function MakeRequest(test){
...............
}
$test = $row['id'];//your id field
<input type="button" class="addActivity" onclick="MakeRequest(<?=$test?>);" value="Activiteit toevoegen" data-activity="' . $row['ActivityID'] . '">

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