Solved

php causing jquery issue with dynamic div assignment

Posted on 2010-11-11
8
480 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
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Github api to fetch the number of collaborators in a git repo 1 25
converting document.write() to innerHTML 7 43
arrays and radio buttons 10 36
deprecated mysql extensions 1 22
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, …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

685 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