jQuery Effects in PHP While Loop - php

Ok I have a list of featured paintings to show on the Index.
I am displaying them using a while loop to get the details from the database.
I want to create a jQuery effect for when the user hovers over the image, the div of that picture appears.
The problem is is that if i were to hover on the first one, the first one's div is ok, but if i were to hover and leave the second one, it would affect the first one. Code below:
Script
<script>
$(document).ready(function(){
$("#featuredImage img").hover(function(){
$("#details").fadeOut();
});
});
</script>
PHP While
<ul id="featured">
<?php
$result = mysqli_query($con,"SELECT * FROM paintings WHERE featured=1");
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$name = $row['name'];
$desc = $row['longDesc'];
$cost = $row['cost'];
$qty = $row['quantity'];
$img = $row['imageFilename'];
$type = $row['type'];
echo "
<li id='featuredImage'>
<div id='featuredImage'><div id='details'>$name</div><img src='/$img'></div>
</li>";
}
?>
</ul>

Try this:
$(document).ready(function(){
$(".featuredImage img").hover(function(){
$(this).siblings(".imgDetails").fadeOut();
});
});
ID's are meant to be unique, use classes instead to match my code above... something like this:
<li class='imageWrap'>
<div class='featuredImage'><div class='imgDetails'>$name</div><img src='/$img'></div>
</li>
Demonstration: http://jsfiddle.net/UHXqd/

What your trying to do is easy to achieve:
Basically change $("#details").fadeOut(); to $(this).siblings("#details").fadeOut();.
But there are other things wrong with your code too:
You have multiple domElements with the same ID, what is quite unfortunate, IDs should be unique.
My advice: change the echo to
<li class='imageContainer'>
<div class='featuredImage'><div class='details'>$name</div><img src='/$img'></div>
</li>
And from here on dont use the '#' in the selectors, use the '.' to select classes, not ids.
$(".featuredImage img").hover(function(){
$(this).siblings(".details").fadeOut();
});
You should use siblings() because the details-div is on the same level as the image.

Related

$_GET not working when trying to view php image in a lightbox style

I have something that im currently working on, however it appears that the $_GET doesn't completely work.
I have a JavaScript light box that brings up an image in a little window, this works however i can only guess that it is using the same URL over and over again.
However when i view the source for the page (and even click one of the links in the source) it will display the correct data.
But the lightbox only seems to display the first image.
This is the JavaScript
<script>
//Checkes if any key pressed. If ESC key pressed it calls the lightbox_close() function.
window.document.onkeydown = function (e)
{
if (!e){
e = event;
}
if (e.keyCode == 27){
lightbox_close();
}
}
</script>
<script>
//This script makes light and fade divs visible by setting their display properties to block.
//Also it scrolls the browser to top of the page to make sure, the popup will be on middle of the screen.
function lightbox_open(){
window.scrollTo(0,0);
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
</script>
<script>
//This makes light and fade divs invisible by setting their display properties to none.
function lightbox_close(){
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
</script>
I wont show the CSS i dont think thats relivant (If someone wants it then ask away)
The relevant part that creates the links is this, its part of a ForEach statement all PHP
$i = 0;
foreach ($nrows as $nrow)
{
$id = $nrow['id'];
$rid = $nrow['RaidID'];
$bid = $nrow['BossID'];
$normal = $nrow['NormalKills'];
$heroic = $nrow['HeroicKills'];
$boss = substr($nrow['BossName'], 0, 3);
$p1 = $id + $bid.".php";
$image = $boss . $p1;
#echo $image;
echo $bid;
if ($oid != $rid)
{
$i = 0;
}
if ($i == 0) {
?><td style="width: 176px;"><center><b><?php echo $nrow['raid']; ?> </b></center></td> </tr><?php
$i++;
}
?><tr><td style="width: 176px;"><div align="left"><?php echo $nrow['BossName']; ?><div id="light"><img src="bossdata/template.php?boss=<?php echo $bid;?>"></a></div><div id="fade" onClick="lightbox_close();"></div>
</div>
<?php
if ($heroic == 0)
{
if ($normal > 0)
{
echo '<img src="images/whiteskull.png" align="right" alt="Normal Kill">';
}
else
{
echo '<img src="images/redx.png" align="right" alt="Not Killed">';
}
}
else
{
echo '<img src="images/redskull.png" align="right" alt="Normal Kill">';
}
?>
</td></tr><?php
$oid = $id;
}
Now this all works, and it actually displays an image with data, however no matter what link i click the boss data is always from the first one on the list.
To me this means that the data is getting through, and reaching the the right parts on image so its "Working", but all the links do the same thing and show the same data :(
*Removed last code Bulk
You have multiple div with the same ID "light" since you create them in a foreach loop.
<div id="light">
Your function lightbox_open() opens all the divs that have id "light".
document.getElementById('light').style.display='block';
That's why you always see the first lightbox. Because the others are behind the first one.
you should try something like this :
function lightbox_open(elem){
window.scrollTo(0,0);
elem.getElementByClass('light').style.display='block';
elem.getElementByClass('fade').style.display='block';
}
And change this :
<a href="#" onclick="lightbox_open();">
By this :
<a href="#" onclick="lightbox_open(this);">
And replace id by class in your div definition :
<div class="light">
$_GET is working correctly in your code.
The issue is in the way you are combining JavaScript and PHP in the second code box. First, all of your divs have the same ID: "light" which is wrong because they all IDs are meant to be unique within the HTML document. You need to identify them uniquely, for example appending the BossID to them.
After identifying each div uniquely you'll have to edit lightbox_open and lightbox_close so they can receive the BossID of the divs that you want to show and hide.

how to get a PHP script to make javascript in li elements

My PHP script queries a database and returns the rows as li elements to a div in a jQuery Dialog. It does this by building an array in the PHP while loop that processes the query row responses. Each li element has some data, an HTML button, and some javascript to execute on that li element when the button is clicked.
If I write "bad HTML" with the same id for each li element, the javascript executes, but only on the first li element. When I write "good HTML" with a unique id for each li element, I can't get the javascript to execute. I've researched and tried lots of things, but can't find anything this complicated to fix this. What should I do? Here's the stripped down code. The problem seems to be in the lengthy $error_ListActives line, but I'm open to suggestions.
$rowCount = 0;
while ($row = mysql_fetch_array($fetch)) {
$storedStreetAddress = $row["streetAddress"];
$storedCity = $row['city'];
$error_NumberOfActives = "<li>Welcome back. You have . . .</li>";
$errorMessages[0] = $error_NumberOfActives;
$idMaker = "inactive" . $rowCount;
$error_ListActives = "<li> $storedStreetAddress, $storedCity $idMaker
<button type='button' id=$idMaker onclick='makeInactive()'>Pause this</button>
<script type='text/javascript'>function makeInactive()
//do stuff
{document.getElementById($idMaker).innerHTML='Inactive Completed';}
</script> </li>";
$errorMessages[] = $error_ListActives;
$rowCount++;
}
foreach( $errorMessages as $statusMessage ) {
echo $statusMessage;
}
Please be specific, and code is helpful. I don't follow general instructions well in this area, as I'm a newbie with PHP.
You're going to end up with a lot of problems here because you are writing your javascript function inside a while loop. That means that you will get several copies of the same function, and only the last one is going to actually fire!
To fix this, write a generic javascript function for makeInactive(id) and then just call it with the id of the element you are working on.
Outside of the php loop:
<script type='text/javascript'>function makeInactive(id)
//do stuff
{document.getElementById(id).innerHTML='Inactive Completed';}
</script>
Then change the php loop to:
while ($row = mysql_fetch_array($fetch)) {
$storedStreetAddress = $row["streetAddress"];
$storedCity = $row['city'];
$error_NumberOfActives = "<li>Welcome back. You have . . .</li>";
$errorMessages[0] = $error_NumberOfActives;
$idMaker = "inactive" . $rowCount;
$error_ListActives = "<li> $storedStreetAddress, $storedCity $idMaker
<button type='button' id='$idMaker' onclick='makeInactive($idMaker)'>Pause this</button>
</li>";
$errorMessages[] = $error_ListActives;
$rowCount++;
}
Why not:
<button onClick="makeInactive(<?php echo $row['id'] ?>);">...</button>
embed the ID code as a parameter to your MakeInactive() call. Other alternatives are to simply use some DOM, e.g.
<li id="xxx"><button onclick="makeInactive(this);">...</button></li>
<script>
function makeInactive(el) {
el.getParent('li').disable(); // not real code, but shows the basic idea
}
</script>
First of all, you're creating the same exact function multiple times on your page. Your other buttons don't know which makeInactive() function to use. Why don't you give all of your buttons the same class, and then create ONE function that is included on the page that fires when the buttons are clicked.
No offense, but this is kind of bad markup here.

Making A List Using PHP And NestedSortable

I'm attempting to make my own CMS and one thing I wanted to do was make it so I could reorder and change the navigation elements in the CMS. I found a plugin called NestedSortable that let me do this. I used it and had a lot of trouble with it, so I got my expert PHP friend to help me do it. She sat down, struggled for a bit and then got it to work.
Well, the idiot I was, when I got home later that day I sat down, took my local copy, added a something to it and uploaded it to the server... not realizing I had forgotten to download the newer version! So poof, all my friend's work is gone and I'm stuck with a navigation adjustment that doesn't work.
I lost the index.php (that displays it on the page) file but I saved the nav_adjust.php (that inputs it into the database). All I want is to be able to re-order the navigation and send it to the database to be displayed correctly on refresh. The information is send to nav_adjust.php when the submit button is pressed.
The only limitation is that the navigation can only have 3 levels to it (primary, child and grandchild). My navigation looks like when they're all primary. I have alerted back the echo for all the images so you can see what nav_adust.php is doing:
(Please note the array values.)
This is as if there was one child on a parent:
This is as if there was two grandchildren on a child:
And this is mixed:
My index.php file, which doesn't work anymore, looks like this:
<form method="post" action="nav_adjust.php"> <!--This form posts to nav_adjust.php-->
<ol id="pageList">
<?php
$nav = mysql_query("SELECT * FROM `".$name['Website']);
$num = 0;
while( $col_nav = mysql_fetch_assoc($nav) ){
if ($col_nav['orderId'] != 0) {
echo "<li id='list_".$col_nav['id']."'>
<div>Example Title</div>";
} else {
echo "<ol>
<li id='list_".$col_nav['id']."'>
<div><h1>Example Title</div>";
</li>
</ol>\n";
}
echo "</li>\n";
++$num;
}
?>
</ol>
<button type='submit'>Update</button>
</form>
<script>
$(document).ready(function(){
$('#pageList').nestedSortable({
/*option that don't matter*/
});
$("button").on('click', function(event){
serialized = $('ol#pageList').nestedSortable('serialize');
$.post( "nav_adjust.php", serialized, function( data ) {
alert( data );
});
return false;
});
});
</script>
Again, the above code doesn't work. Instead of making a list item look like this:
<ol>
<li>
<ol>
<li></li>
...
</ol>
</li>
...
</ol>
It makes it look like this (note the closed li tag before the ol):
<ol>
<li></li>
<ol>
<li></li>
</ol>
...
</ol>
And this is the nav_adjust.php that my friend did for me which works beautifully if given the right information from index.php
$list = $_POST['list'];
$num = 1;
foreach ($list as $key => $value ) {
if ($value == "null") {
//$value = $num;
mysql_query("UPDATE `myTable` SET orderId=".$num.", parent='null' WHERE id=".$key."");
$text .= "UPDATE `myTable` SET orderId=".$num.", parent='null' WHERE id=".$key."\n\n";
} else {
$query = "UPDATE `myTable` SET orderId=". $num .", parent=".$value;
$text .= "UPDATE `myTable` SET orderId=". $num .", parent=".$value."\n\n";
$var = $list[$value];
if ( $var != null && $list[$var] != null ) {
$query .= ", grandchild = 1";
}
$query .= " WHERE id=".$key;
mysql_query($query);
}
$num++;
}
echo "Content is below\n";
print_r( $_POST['list']);
echo $text;
So, as a recap, I have a navigation that submits serialized data from index.php to nav_adjust.php which then submits it into a database (and echos it back so I know what I did). Then index.php, upon refresh, should keep the list items in place, with all children as children and such. But I overwrite index.php and have no idea how my friend did it.
My table fields are (before I forget):
id, title, orderId (parent), parent (child) and grandchild.
I was meaning to change the names of orderId and parent to make it less confusing but I never did :(
If somebody could help me, I'd be so very thankful.
If there is any other information I can give you, please ask!
After hours of struggling, I had the genius idea of asking GoDaddy if they backed up files and directories, and they did! So I got my file back. For anybody interested, the code missing on index.php looked like this (where $name['website'] is 'myTable'):
$parents = mysql_query("SELECT * FROM `".$name['Website']."` WHERE parent = 0 ORDER BY `orderId` ASC");
while($parent = mysql_fetch_array($parents)){
echo "<li id='list_".$parent['id']."'>
<div>
<span class='disclose'>
<span></span>
</span>
<span class='title'>
<a href='mod.php?id=".$parent['id']."'>".stripslashes($parent['page'])."</a>
</span>
</div>";
// Get chil elements
$children = mysql_query("SELECT * FROM `".$name['Website']."` WHERE parent = " . $parent['id'] . " ORDER BY `orderId` ASC") or die(mysql_error());
while($child = mysql_fetch_array($children)){
echo "<ol>
<li id='list_".$child['id']."'>
<div>
<span class='disclose'>
<span></span>
</span>
<span class='title'>
<a href='mod.php?id=".$child['id']."'>".stripslashes($child['page'])."</a>
</span>
</div>";
# Get grandchild elements
# (Please consider making an recursive function or so out of this if you plan to have grand grand children etc.,
# Because if you create new whiles manually for every instance, this is gonna look pretty darn ugly.
# Also, it makes it impossible to have an unknown depth.)
$grandchildren = mysql_query("SELECT * FROM `".$name['Website']."` WHERE parent = " . $child['id'] . " AND grandchild = 1 ORDER BY `orderId` ASC");
while($grandchild = mysql_fetch_array($grandchildren)){
echo "<ol>
<li id='list_".$grandchild['id']."'>
<div>
<span class='disclose'>
<span></span>
</span>
<span class='title'>
<a href='mod.php?id=".$grandchild['id']."'>".stripslashes($grandchild['page'])."</a>
</span>
</div>
</li>
</ol>\n";
}
// Close child
echo "</li>
</ol>\n";
}
// Close parent
echo "</li>\n";
}
?>

Moving JavaScript into PHP

I'm just starting out with PHP, and I am attempting to move some jQuery ajax into PHP. Here is my PHP file:
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>";
}
include 'closedb.php';
?>
Here is my current js function:
//Add Agency content
$("ul.top-level").on("click", "li.agency a", function (event) {
if($(this).next().length) {
var numbs = $(this).attr("href").match(/id=([0-9]+)/)[1];
showContentAgency(numbs, this);
} else {
$(this).closest('ul').find('a').removeClass('sub-active');
}
event.preventDefault();
});
And here is the showContentAgency(); function:
function showContentAgency(id, elem) {
$.post("assets/includes/contentAgency.php?id=id", {
id: id
}, function (data) {
$(elem).addClass("nav-active").parent().find("ul").html(data).show();
});
}
What I'd like to do is have PHP render the unordered list rather than have jQuery insert it. This is how it is currently featured in the above PHP file:
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>"
So I would like the PHP to populate the <ul class="agency-sub"> list.
The structure of your code is a little bit unclear to me, but the broad outline is this: You take whatever function is generating the content in contentAgency.php and call that to get the HTML, then stick that inside when you're building up the list.
Php can not access the DOM of the page like Jquery can. If you wanted to access the DOM with Php, you would have to parse the entire web page, which is probably impractical for what you want to do. Php can only modify the page before it is loaded by the browser. If you want to run code after page load, you have to use javascript.
We might be able to help you more if you post more of your code, as we currently don't know what the page's code looks like.
Is this a list inside list?
By the way you can write php code like below, it is more readable
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class='agency'><a href='contentAgency.php?id=$id'>$name</a><ul class='agency-sub'></ul></li>";
}
include 'closedb.php';
?>
if you are using double quotes in echo you can use single quotes inside.
I'm uncertain as to what exactly you want but it sounds like you're looking for the 'foreach' loop. When I wanna populate a list of stuff from a result set i simple use:
<ul>
<? foreach($result as $object) ?>
<li><?=$object?></li>
<? endforeach; ?>
</ul>
foreach acts a for loop but doing all the logic in the background. Hope this helps.

php array and jquery add class

I am trying to get desks highlighted that are available based off of a form that asks for the the day, time start and time end. I am able to echo out all the desks that are available, but I cant get the jquery to work with it.
foreach ($allData as $desk => $id){
foreach ($id as $computer){?>
<div id="<?php echo $desk?>"></div><?php
}
}
<style>
.availableDesk{
background: #000000
}
</style>
<script>
$(document).ready(function() {
jQuery( " <?php echo $desk ?> " ), addClass('availableDesk') ;
})
</script>
DESKS:
<ul class="tabs">
<li id="1A"><div id="ddesk"></div></li>
<li id="1B"><div id="ddesk"></div></li>
<li id="1C"><div id="ddesk"></div></li>
</ul>
You're missing the ?> at the end of your PHP block.
<?php
foreach ($allData as $desk => $id){
foreach ($id as $computer){?>
<div id="<?php echo $desk?>"></div><?php
}
} // You need a "?>" here
?>
There are a few things wrong with your jQuery code. First off, if $desk is an ID, you need to do $('#ID'). Second, you have a comma before addClass instead of a period.
jQuery("#<?php echo $desk ?>").addClass('availableDesk');
P.S. HTML ID's aren't supposed to start with a number. Also, you cannot have multiple elements with the same ID, I suggest you use classes instead.
I can see a couple of potential issues here...
jQuery( "<?php echo $desk ?>" ), addClass('availableDesk') ;
Syntactically, I think this should be:
jQuery("#<?php echo $desk ?>").addClass('availableDesk');
Note the # in the selector, this tells jQuery that you are looking for an id. The addClass method is available on the returned items, so you need a stop (.) not a comma (,)
The other gotcha is that you are writing the id in a foreach loop in PHP - I presume that each desk has a unique id - when you write jQuery("#<?php echo $desk ?>") the statement is outside of the foreach loop, so it won't match the ids you are targeting.
If you know that the desk is available in PHP, the best option would be to set the class as you write the desk...
<div id="<?php echo $desk?>" class="availableDesk"></div>

Categories