Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

php causing jquery issue with dynamic div assignment

Posted on 2010-11-11
8
Medium Priority
?
483 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 2000 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:Justin Mathews
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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:Justin Mathews
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

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
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 …

688 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