Solved

php causing jquery issue with dynamic div assignment

Posted on 2010-11-11
8
482 Views
Last Modified: 2012-05-10
Hello,

I have the below jquery script that iterates through xml from album.php and dynamically constructs a DIV with nested IMG tags.  I'm attempting to use jquery to assign a tooltip element to the IMG tags within the "albumdiv" element.  The for loop (labeled snippet 1) allows the assignment of the tooltip, while the code withing the GET request loops from album.php doesn't work.  I've included album.php as well, any ideas?  

JQuery Script:
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
	loadAlbums();			 
	$("#albumdiv img[title]").tooltip({
					offset: [10, 2],
					effect: 'slide'
			})
	.dynamic({ bottom: { direction: 'down', bounce: true } });
});
function loadAlbums(){
	//code snippet 1
	var album_div = $('#albumdiv');
	for (i=0;i<4;i++)
	{
		var albumImg = $(document.createElement("img"))
		.attr("src", "http://static.flowplayer.org/tools/img/photos/2.jpg")
		.attr("title", "test works")
		.attr("width", "75")
		.attr("height", "75");
		album_div.append(albumImg);
	}
	//code snippet 2
	$.get("album.php", function(theXML){
		$('album',theXML).each(function(i){  
			var albumImg = $(document.createElement("img"))
					.attr("src", "http://static.flowplayer.org/tools/img/photos/2.jpg")
					.attr("title", "test doesn't work")
					.attr("width", "75")
					.attr("height", "75");
					album_div.append(albumImg);
		});
	});		 
}

Open in new window


album.php
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); 
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); 
header("Cache-Control: no-cache, must-revalidate" ); 
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=utf-8");
$directory = "swfupload/uploads/";
$xml = '<?xml version="1.0" ?><albums>';
$con = mysql_connect('credentials'');
$show_dialog='display:none;';
if (!$con){
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("conn string", $con);
$sql="SELECT * FROM ALBUM_NEW"; 
$result=mysql_query($sql); 
while ($row=mysql_fetch_array($result)){
    $albumId=$row["ID"];
	$albumTitle=$row["TITLE"]; 
	$albumCover=$row["COVER_IMAGE"];	
	$xml .= "<album>";
	$xml .= "<id>".$albumId."</id>";
	$xml .= "<title>".$albumTitle."</title>";
	$xml .= "<albumCover>".$albumCover."</albumCover>";
	$xml .= "</album>";
} 	
mysql_close($con);			
$xml .= '</albums>';
echo $xml;
?>

Open in new window

0
Comment
Question by:cgray1223
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +1
8 Comments
 
LVL 31

Accepted Solution

by:
Frosty555 earned 500 total points
ID: 34119047
I think the problem is that you're loading the dynamic DIV tags in via an asynchronious AJAX query, so when you call the $().tooltip() call, the ajax hasn't returned yet. As a result only the first div tags (the non dynamic ones) are tooltip-enabled.

I think you need to copy your lines that initiate the tooltip, and make sure you put it inside the completion function of your AJAX query as well.


//code snippet 2
      $.get("album.php", function(theXML){
            $('album',theXML).each(function(i){  
                  var albumImg = $(document.createElement("img"))
                              .attr("src", "http://static.flowplayer.org/tools/img/photos/2.jpg")
                              .attr("title", "test doesn't work")
                              .attr("width", "75")
                              .attr("height", "75");
                              album_div.append(albumImg);


                  // Enable tooltips on these new DIV tags
                  ("#albumdiv img[title]").tooltip({
                              offset: [10, 2],
                              effect: 'slide'
                                    })
                        .dynamic({ bottom: { direction: 'down', bounce: true } });




            });
      });      


0
 
LVL 17

Expert Comment

by:jrm213jrm213
ID: 34124020
hi, there are many ways to do things in jquery, the way I would have written the script to iterate the album elements from your album.php get would be like this

$.get("album.php",function(theXML){
    $(theXML).find('album').each(function(i){
           var albumImg = $(document.createElement("img"))
         .attr("src", "http://static.flowplayer.org/tools/img/photos/2.jpg")
         .attr("title", "test doesn't work")
         .attr("width", "75")
         .attr("height", "75");
         album_div.append(albumImg);
    });
});            

0
 
LVL 16

Expert Comment

by:jmatix
ID: 34124033
You need to construct a DOM from the XML response from PHP. Then only you can get the <album> elements with find(). Change your code snippet 2 as below:
//code snippet 2
$.get("album.xml", function(theXML){
	var doc = null;
	if (window.ActiveXObject) {
		doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.loadXML(theXML);
	  } else if (window.DOMParser) {
		doc = (new DOMParser).parseFromString(theXML, 'text/xml');
	  }

	$(doc).find("album").each(function(i){
		var albumImg = $(document.createElement("img"))
				.attr("src", "http://static.flowplayer.org/tools/img/photos/2.jpg")
				.attr("title", $(this).children("title").text())
				.attr("width", "75")
				.attr("height", "75");
				album_div.append(albumImg);
	});
});

Open in new window

0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 17

Expert Comment

by:jrm213jrm213
ID: 34124088
my understanding was as long as the result retrieved reports itself as xml then you can use jquery's functions on it directly?

from jquery: The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.
0
 
LVL 16

Expert Comment

by:jmatix
ID: 34124168
@jrm213jrm213:

You are right. In this case since the response header says: Content-Type: text/xml, JQuery will construct an XML DOM and pass it to the callback.
0
 

Author Comment

by:cgray1223
ID: 34128311
Thanks all for you're ideas. I've tried all and I've been unsuccessful in getting the tooltip to show on the dynamic div/image.  

jmatix - I tried your suggestion but replaced album.xml with album.php as I think that was a typo in your response.  In IE I get a type mismatch JS error on the doc.loadXML(theXML); line.  I tried changing album.php's content-type to application/xml as well but both threw the same JS type mismatch error. In Firefox/Chrome it seems to construct the DOM element but never executes my alert("for loop"); in the below snippet so I'm thinking the document structure isn't being created properly.  Any ideas as to why?  Thanks for the help.


$.get("album.php", function(theXML){
	var doc = null;
	if (window.ActiveXObject) {
		doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.loadXML(theXML);
	  } else if (window.DOMParser) {
		doc = (new DOMParser).parseFromString(theXML, 'text/xml');
	  }
	alert(theXML);
	$(doc).find("album").each(function(i){
	alert("for loop");
		var albumImg = $(document.createElement("img"))
				.attr("src", "http://static.flowplayer.org/tools/img/photos/2.jpg")
				.attr("title", $(this).children("title").text())
				.attr("width", "75")
				.attr("height", "75");
				album_div.append(albumImg);
	});
});

Open in new window

0
 

Author Comment

by:cgray1223
ID: 34132207
I solved my issue...the tooltip assignments must go directly on the dynamic img element, close to what Frosty555 suggested.  
var albumImg = $(document.createElement("img"))
					.attr("src", "swfupload/uploads/"+ albumCoverImagePath)
					.attr("title", albumTitle)
					.attr("width", "75")
					.attr("height", "75")
					.click(function(){
						loadGallery(albumId, albumTitle);
						$("#tabs").tabs("option", "selected", 2);					
					})
					.tooltip({
						offset: [10, 2],
						effect: 'slide'
					})
					.dynamic({ bottom: { direction: 'down', bounce: true } });

Open in new window

0
 
LVL 31

Expert Comment

by:Frosty555
ID: 34134145
Your code and my code are identical aside from the fact that you're doing it all in one statement instead of executing two separate jquery selectors.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question