Solved

php causing jquery issue with dynamic div assignment

Posted on 2010-11-11
8
469 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
  • 2
  • 2
  • 2
  • +1
8 Comments
 
LVL 31

Accepted Solution

by:
Frosty555 earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 17

Expert Comment

by:jrm213jrm213
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 16

Expert Comment

by:jmatix
Comment Utility
@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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
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…
The viewer will learn how to count occurrences of each item in an array.

762 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now