Gallery con Tag foto: problema doppia chiamata ajax con JQuery

Scrabionau77

Nuovo Utente
27 Set 2008
5
0
0
Buongiorno a tutti.
Sto implementando in un sito php una photogallery con jcarousel e un sistema di tag foto simile a quello di facebook.
Sia la gallery che il sistema di tag funzionano, ma sull'inserimento dei tag ho un'anomalia: i tag che inseriscono vengono duplicati, ossia inseriti più volte nel database.
Vi riporto un estratto del codice:

FILE gallery.php (un estratto html, privo di fogli di stile, della pagina principale)
HTML:
<div id="rg-gallery" class="rg-gallery">
		                <div class="rg-thumbs">
		                    <!-- Elastislide Carousel Thumbnail Viewer -->
		                    <div class="es-carousel-wrapper">
		                        <div class="es-nav">
		                            <span class="es-nav-prev">Previous</span>
		                            <span class="es-nav-next">Next</span>
		                        </div>
		                        <div class="es-carousel">
		                            <ul>
		                                <li>
		                                    <a href="#">
		                                    <img src="images/gallery/14-65x65.jpg" data-large="images/gallery/14.jpg" alt="Photo #14" data-description="Descrizione della prima foto" data-picid="1" />
		                                    </a>
		                                </li>
		                                <li>
		                                    <a href="#">
		                                    <img src="images/gallery/13-65x65.jpg" data-large="images/gallery/13.jpg" alt="Photo #13" data-description="Descrizione della seconda foto" data-picid="2" />
		                                    </a>
		                                </li>
		                            </ul>
		                        </div>
		                    </div>
		                </div>
		            </div>

<script type='text/javascript' src='js/jquery.tmpl.min.js'></script>
			        <script type='text/javascript' src='js/jquery.elastislide.js'></script>
					<script type='text/javascript' src='js/gallery.js'></script>
					<script id="img-wrapper-tmpl" type="text/x-jquery-tmpl">
					    
                        <div class="rg-image-wrapper">
					        {{if itemsCount > 1}}
					            <div class="rg-image-nav">
					                <a href="#" class="rg-image-nav-prev">Previous Image</a>
					                <a href="#" class="rg-image-nav-next">Next Image</a>
					            </div>
					        {{/if}}
                            <div class="rg-image" id="imgtag"></div>
					        <div id="tagbox_dp"></div>
                            <div class="rg-loading"></div>
					    </div>
					    <div class="rg-caption-wrapper">
					        <div class="rg-caption" style="display:none;">
					            <p></p>
                                <div>In questa foto: ....</div>
                                <div>Commenti: ....</div>
					        </div>
					    </div>
					</script>
  <div id="taglist_dp"> 
    <span class="tagtitle">List of Tags</span> 
    <ol> 
    </ol> 
  </div>

Questo invece è il file gallery.js contenente le funzioni relative alla gallery e ai tag
HTML:
jQuery(function($) {

	$.fn.imagesLoaded 		= function( callback ) {
	var $images = this.find('img'),
		len 	= $images.length,
		_this 	= this,
		blank 	= 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';


	function triggerCallback() {
		callback.call( _this, $images );
	}

	function imgLoaded() {
		if ( --len <= 0 && this.src !== blank ){
			setTimeout( triggerCallback );
			$images.off( 'load error', imgLoaded );
		}
	}

	if ( !len ) {
		triggerCallback();
	}

	$images.on( 'load error',  imgLoaded ).each( function() {
		// cached images don't fire load sometimes, so we reset src.
		if (this.complete || this.complete === undefined){
			var src = this.src;
			// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
			// data uri bypasses webkit log warning (thx doug jones)
			this.src = blank;
			this.src = src;
		}
	});

	return this;
	};

	// gallery container
	var $rgGallery			= $('#rg-gallery'),
	// carousel container
	$esCarousel			= $rgGallery.find('div.es-carousel-wrapper'),
	// the carousel items
	$items				= $esCarousel.find('ul > li'),
	// total number of items
	itemsCount			= $items.length;
	
	Gallery				= (function() {
			// index of the current item
		var current			= 0, 
			// mode : carousel || fullview
			mode 			= 'carousel',
			// control if one image is being loaded
			anim			= true,
			init			= function() {

                
                // (not necessary) preloading the images here...
				$items.add('<img src="images/ajax-loader.gif"/><img src="images/black.png"/>').imagesLoaded( function() {
					// add options
					//_addViewModes();
					
					// add large image wrapper
					_addImageWrapper();
					
					// show first image
					_showImage( $items.eq( current ) );
						
				});
				
				// initialize the carousel
				if( mode === 'carousel' )
					_initCarousel();
				
			},
			_initCarousel	= function() {
				
				// we are using the elastislide plugin:
				// http://tympanus.net/codrops/2011/09/12/elastislide-responsive-carousel/
				$esCarousel.show().elastislide({
					imageW 	: 65,
					onClick	: function( $item ) {
						if( anim ) return false;
						anim	= true;
						// on click show image
						_showImage($item);
						// change current
						current	= $item.index();
					}
				});
				
				// set elastislide's current to current
				$esCarousel.elastislide( 'setCurrent', current );
				
			},
			_addViewModes	= function() {
				
				// top right buttons: hide / show carousel
				
				var $viewfull	= $('<a href="#" class="rg-view-full"></a>'),
					$viewthumbs	= $('<a href="#" class="rg-view-thumbs rg-view-selected"></a>');
				
				$rgGallery.prepend( $('<div class="rg-view"/>').append( $viewfull ).append( $viewthumbs ) );
				
				$viewfull.on('click.rgGallery', function( event ) {
						if( mode === 'carousel' )
							$esCarousel.elastislide( 'destroy' );
						$esCarousel.hide();
					$viewfull.addClass('rg-view-selected');
					$viewthumbs.removeClass('rg-view-selected');
					mode	= 'fullview';
					return false;
				});
				
				$viewthumbs.on('click.rgGallery', function( event ) {
					_initCarousel();
					$viewthumbs.addClass('rg-view-selected');
					$viewfull.removeClass('rg-view-selected');
					mode	= 'carousel';
					return false;
				});
				
				if( mode === 'fullview' )
					$viewfull.trigger('click');
					
			},
			_addImageWrapper= function() {
				
				// adds the structure for the large image and the navigation buttons (if total items > 1)
				// also initializes the navigation events
                                    
				$('#img-wrapper-tmpl').tmpl( {itemsCount : itemsCount} ).prependTo( $rgGallery ); 
				
				if( itemsCount > 1 ) {
					// addNavigation
					var $navPrev		= $rgGallery.find('a.rg-image-nav-prev'),
						$navNext		= $rgGallery.find('a.rg-image-nav-next'),
						$imgWrapper		= $rgGallery.find('div.rg-image');
						
					$navPrev.on('click.rgGallery', function( event ) {
						_navigate( 'left' );
						return false;
					});	
					
					$navNext.on('click.rgGallery', function( event ) {
						_navigate( 'right' );
						return false;
					});
				
					// add touchwipe events on the large image wrapper
					$imgWrapper.touchwipe({
						wipeLeft			: function() {
							_navigate( 'right' );
						},
						wipeRight			: function() {
							_navigate( 'left' );
						},
						preventDefaultEvents: false
					});
				
					$(document).on('keyup.rgGallery', function( event ) {
						if (event.keyCode == 39)
							_navigate( 'right' );
						else if (event.keyCode == 37)
							_navigate( 'left' );	
					});
                    
					
				}
				
			},
			_navigate		= function( dir ) {
				
				// navigate through the large images
				
				if( anim ) return false;
				anim	= true;
				
				if( dir === 'right' ) {
					if( current + 1 >= itemsCount )
						current = 0;
					else
						++current;
				}
				else if( dir === 'left' ) {
					if( current - 1 < 0 )
						current = itemsCount - 1;
					else
						--current;
				}
				
				_showImage( $items.eq( current ) );
				
			},
			_showImage		= function( $item ) {
				
				// shows the large image that is associated to the $item
				
				var $loader	= $rgGallery.find('div.rg-loading').show();
				
				$items.removeClass('selected');
				$item.addClass('selected');
					 
				var $thumb		= $item.find('img'),
					largesrc	= $thumb.data('large'),
					title		= $thumb.data('description');
                    picid	    = $thumb.data('picid'); // variabile utilizzata nella sezione tag
				
                
                $('<img/>').load( function() {
					
					$rgGallery.find('div.rg-image').empty().append('<img src="' + largesrc + '"/>');
					
					if( title )
						$rgGallery.find('div.rg-caption').show().children('p').empty().text( title );
					else  
					    $rgGallery.find('div.rg-caption').hide().children('p').empty();
					
					$loader.hide();
					
					if( mode === 'carousel' ) {
						$esCarousel.elastislide( 'reload' );
						$esCarousel.elastislide( 'setCurrent', current );
					}
					
					anim	= false;
					
					$rgGallery.find('div.rg-image-wrapper').css( 'max-width', $('div.rg-image img', $rgGallery).width() + 'px' );
					
				}).attr( 'src', largesrc );

                //***** FUNZIONI RELATIVE AL TAG FOTO *****//
                    var counter = 0;
                    var mouseX = 0;
                    var mouseY = 0;
                    
                    //genera box di inserimento tag
                    $("div.rg-image").click(function(e){ // make sure the image is click
                      var imgtag = $(this).parent(); // get the div to append the tagging list
                      mouseX = e.pageX - $(imgtag).offset().left; // x and y axis
                      mouseY = e.pageY - $(imgtag).offset().top;
                      $('#tagit_dp').remove(); // remove any tagit div first
                      $(imgtag).append('<div id="tagit_dp"><div class="box"></div><div class="name"><div class="text">Tagga gli amici</div><input type="text" name="txtname" id="tagname" /><input type="button" name="btnsave" value="Save" id="btnsave" /><input type="button" name="btncancel" value="Cancel" id="btncancel" /></div></div>');
                      $('#tagit_dp').css({top:mouseY,left:mouseX});
                      $('#tagname').focus();
                    });
                    
                    
                    // inserisce nuovi tag
                    $('#tagit_dp #btnsave').live('click',function(){
                      name = $('#tagname').val();
                      
                      $.ajax({
                        type: "POST", 
                        url: "utility_tag_savetag.php", 
                        data: "name=" + name + "&pic_x=" + mouseX + "&pic_y=" + mouseY + "&pic_id=" + picid + "&type=insert",
                        cache: true, 
                        success: function(data){
                          viewtag(picid);
                          $('#tagit_dp').fadeOut();
                        }
                      });
                      
                    });
                    
                    // annulla inserimento tag
                    $('#tagit_dp #btncancel').live('click',function(){
                      $('#tagit_dp').fadeOut();
                    });
                    
                    // passaggio mouse su lista tag
                    $('#taglist_dp li').live('mouseover mouseout',function(event){
                      id = $(this).attr("rel");
                      if (event.type == "mouseover"){
                        $('#view_' + id).show();
                      }else{
                        $('#view_' + id).hide();
                      }
                    });
                    
                    // rimuove un tag
                    $('#taglist_dp li a.remove').live('click',function(){
                      id = $(this).parent().attr("rel");
                      // get all tag on page load
                      $.ajax({
                        type: "POST", 
                        url: "utility_tag_savetag.php", 
                        data: "tag_id=" + id + "&type=remove",
                        success: function(data){
                        viewtag(picid);
                        }
                      });
                    });
                    
                    
                    function viewtag(pic_id)
                    {
                      // get the tag list with action remove
                      $.ajax({
                        type: "POST", 
                        url: "utility_tag_savetag.php", 
                        data: "pic_id=" + pic_id + "type=0",
                        cache: true, 
                        success: function(data){
                          $('#taglist_dp ol').html(data);
                        }
                      });
                      
                      // get the tag list for boxes
                      $.ajax({
                        type: "POST", 
                        url: "utility_tag_taglist.php", 
                        data: "pic_id=" + pic_id,
                        cache: true, 
                        success: function(data){
                          $('#tagbox_dp').html(data);
                        }
                      });
                    }
                    
                    viewtag(picid); // get all tag on page load
                    // FINE FUNZIONI RELATIVE A TAG FOTO
                    

			},
			addItems		= function( $new ) {
			
				$esCarousel.find('ul').append($new);
				$items 		= $items.add( $($new) );
				itemsCount	= $items.length; 
				$esCarousel.elastislide( 'add', $new );
			
			};
		
		return { 
			init 		: init,
			addItems	: addItems
		};
	
	})();

	Gallery.init();
	
	/*
	Example to add more items to the gallery:
	
	var $new  = $('<li><a href="#"><img src="images/thumbs/1.jpg" data-large="images/1.jpg" alt="image01" data-description="From off a hill whose concave womb reworded" /></a></li>');
	Gallery.addItems( $new );
	*/
});

In particolare l'anomalia è questa:
- al primo caricamento della pagina (quindi sulla prima foto caricata), il sistema funziona bene
- se visualizzo una foto diversa dalla prima, per ciascun tag che inserisco ne vengono memorizzati almeno due.

La chiamata Ajax di inserimento tag viene quindi eseguita più volte. Ma non essendo molto esperto di jquery non riesco a risolvere il problema.
Sapete indicarmi dov'è l'errore?
Grazie in anticipo a tutti ;)
 
RISOLTO:
Dopo un po' di prove sono arrivato alla risoluzione. Avevo inserito la chiamata alla funzione di tag nel posto errato.
Vanno invece inserite nella funzione init cioè nell'inizializzazione.
 

Discussioni simili