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
Solved

jquery events not firing on ajax call

Posted on 2013-02-01
19
411 Views
Last Modified: 2013-02-25
I am using Jquery 1.7.2

On initial page load I am executing the following script in an external JS loaded at the end of the page and wrapped in $(document).ready(function(){

          
    $('.accordionContent,.accordionContent-settings').hide();
    $('.accordion-comments').click(function(){
            	var target=$(this).attr('href');
            	if($(target).css('display')=='none')
            	{
            		$(target).show();
            		$(this).text('Hide Comments');
            	}
            	else
            	{
            		$(target).hide();
            		$(this).text('Comments');
            	}
            	return false;
            	});

Open in new window


The code essentially hides the form contained in this unordered list and reveals the form when the "Comments" link is clicked. The wording is then changed to Hide Comment and when clicked again the form is hidden again.


    <ul class="sportswire-posts quarterfont">
    						<li>							
    							<p><a href="/modals.cfm?action=profile_glimpse&script=%2Findex%2Ecfm%2Fgroup%2F3450%2Faction%2Fdashboard&member_id=5" rel="facebox" class="capitalize">Todd John</a> joined the team &quot;<a href="http://shootingattackclinic.playerspace.com/local_sports_teams.cfm?group=628">Mercury</a>&quot;.</p>
    							<p class="comments-date">11:38 AM EST on January 31, 2013</p>
    						</li>						
    											
    						
    							<li class="comments-link">
    								<a href="#comments35800" class="accordion-comments">Comments</a> 
    							</li> 						
    						
    						<li class="accordionContent posts-comments" id="comments35800">
    							
    								<form method="post" action="/index.cfm/group/3450/action/dashboard/m0dal_update/leave_feedback/member_id/68/comment_type/17/id/35800">
    									<ul>
    										<li>
    											<div class="expandingArea">
    												<pre><span></span><br /></pre>
    												<textarea name="str_comment" message="Enter a comment." rows="4" cols="10" required="Yes" html="No" id="str_comment24234"></textarea>											
    											</div>										
    											<div class="pixelspacer10"></div>
    										</li>
    										<li>
    											<input name="Post Comment" type="submit" value="Post Comment" />
    										</li>								
    									</ul>
    								</form>
    																		
    						</li>																				
    					</ul>

Open in new window


The problem is when I make an ajax call to get additional ULS like the the one above (with different ids of course).

    $(document).on("click",'.siteusemore',function()
    		{
    		var ID = $(this).attr("id");
    		var myscript = window.siteusemore_script || null;		
    		if(ID)
    			{
    				$("#siteusemore"+ID).html('<img src="/images/processing.gif" />');					
    				$.ajax({type: "POST",url: myscript,data: "lastmsg="+ ID, cache: false,
    					success: function(html){									
    						$("ol#siteuseupdates").append(html);				
    						$('.accordionContent').empty();						
    						$('.accordionContent').show();																		
    						$('.accordionContent').hide();						
    						$('.accordion-comments').empty();						
    						$('.accordion-comments').show();						
    						$('.accordion-comments').on("click",function(){
    						var target=$(this).attr('href');
    						if($(target).css('display')=='none')
    						{
    							$(target).show();
    							$(this).text('Hide Comments');
    						}
    						else
    						{
    							$(target).hide();
    							$(this).text('Comments');
    						}
    						});																						
    						$("#siteusemore"+ID).remove();						
    					}
    				});				
    			}
    		else
    		{
    			$(".siteusemorebox").html('The End');						
    		}				
    		return false;
    	});

Open in new window


The above method works inconsistently. The hide/show event fires for some items, but not all. I can't seem to figure out why I just can't get it to work for every comment/form combination loaded via ajx. What am I doing wrong?
0
Comment
Question by:ondrejko1
  • 10
  • 9
19 Comments
 
LVL 11

Expert Comment

by:mcnute
ID: 38844523
A quick solution would be to use .live(); it is deprecated starting by jquery 1.8 but it gives the best results for dynamically added content on pages.

I wouldn't attach an event handler to the document itself, it is certainly not best practice. Do you have a wrapping container around your forms?

If that all has no effect, first get rid of all hashes in the href attributes of your hide/show links and make the following change to your jquery show/hide click event:

  $('.accordionContent,.accordionContent-settings').hide();
    $('.accordion-comments').click(function(){
            	var target=$(this).attr('href');
            	if($(target).css('display')=='none')
            	{
            		$('#'+target).show();
            		$(this).text('Hide Comments');
            	}
            	else
            	{
            		$('#'+target).hide();
            		$(this).text('Comments');
            	}
            	return false;
            	});

Open in new window

0
 

Author Comment

by:ondrejko1
ID: 38844640
Removing the hash from my href and adding the above code had no effect. In fact, it didn't respond at all, even before the ajax call.
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38844665
Can you provide us with a fully working example of your code? This will make debugging so much easier. Preferably as a zip package ready to unzip into our local test-environments here.
0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

Author Comment

by:ondrejko1
ID: 38844787
I can prove you with a login to where its located. That sufficient?
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38844792
Yes. That'll be perfect.
0
 

Author Comment

by:ondrejko1
ID: 38844839
http://shootingattackclinic.playerspace.com/index.cfm/group/3450/action/login

username: seolms
password: test


The recent activity feed is the one Im having issues with.
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38844859
It works just fine on my mac in google chrome. Which browser are you using?
0
 

Author Comment

by:ondrejko1
ID: 38844864
This is the ajax call, not the one I included above:
	$(document).on("click",'.siteusemore',function()
		{
		var ID = $(this).attr("id");
		var myscript = window.siteusemore_script || null;		
		if(ID)
			{
				$("#siteusemore"+ID).html('<img src="/images/processing.gif" />');					
				$.ajax({type: "POST",url: myscript,data: "lastmsg="+ ID, cache: false,
					success: function(html){									
					$("ol#siteuseupdates").append(html);											
						$("#siteusemore"+ID).remove();						
						$('.accordionContent').hide();							
				        $('.accordion-comments').on("click",function(){
                        var target=$(this).attr('href');
                        if($(target).css('display')=='none')
                        {
                            $(target).show();
                            $(this).text('Hide Comments');
                        }
                        else
                        {
                            $(target).hide();
                            $(this).text('Comments');
                        }
                        });   					
					}
				});				
			}
		else
		{
			$(".siteusemorebox").html('The End');						
		}				
		return false;
	});

Open in new window

0
 

Author Comment

by:ondrejko1
ID: 38844865
Try all the links, then click the ajax a couple of times. You'll see what I'm talking about. It works sporadically. Usually its on the 3rd ajax call.
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38844868
Change the click event to something like so:

  $('.accordionContent,.accordionContent-settings').hide();
    $('.comments-link').on('click', 'a'. function(){
            	var target=$(this).attr('href');
            	if($(target).css('display')=='none')
            	{
            		$('#'+target).show();
            		$(this).text('Hide Comments');
            	}
            	else
            	{
            		$('#'+target).hide();
            		$(this).text('Comments');
            	}
            	return false;
            	});

Open in new window

0
 
LVL 11

Expert Comment

by:mcnute
ID: 38844873
	$(document).on("click",'.siteusemore',function()
		{
		var ID = $(this).attr("id");
		var myscript = window.siteusemore_script || null;		
		if(ID)
			{
				$("#siteusemore"+ID).html('<img src="/images/processing.gif" />');					
				$.ajax({type: "POST",url: myscript,data: "lastmsg="+ ID, cache: false,
					success: function(html){									
					$("ol#siteuseupdates").append(html);											
						$("#siteusemore"+ID).remove();						
						$('.accordionContent').hide();							
				        $('.comments-link').on("click", "a", function(){
                        var target=$(this).attr('href');
                        if($(target).css('display')=='none')
                        {
                            $(target).show();
                            $(this).text('Hide Comments');
                        }
                        else
                        {
                            $(target).hide();
                            $(this).text('Comments');
                        }
                        });   					
					}
				});				
			}
		else
		{
			$(".siteusemorebox").html('The End');						
		}				
		return false;
	});

Open in new window


Here also.
0
 

Author Comment

by:ondrejko1
ID: 38844951
Did as you advised, still producing unresponsive anchor elements.
0
 

Author Comment

by:ondrejko1
ID: 38845079
Any other ideas?
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38845086
just one question how do i fire the ajax call on the page? It has a lot of areas and functionality. Sorry, just too lazy to seek in the code ;-)
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38845139
Did you try live instead of on

$('.comments-link a').live("click", function(){ ....

Open in new window

0
 

Author Comment

by:ondrejko1
ID: 38851917
Yes, live had no effect.
0
 
LVL 11

Expert Comment

by:mcnute
ID: 38852030
Really strange, the only thing i can advice you is to use the very latest jquery 1.9 instead of 1.7. Maybe that helps.
0
 

Accepted Solution

by:
ondrejko1 earned 0 total points
ID: 38909926
I was making the ajax call twice. It is now set at the document level.
0
 

Author Closing Comment

by:ondrejko1
ID: 38924991
figured it out myself
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Java script read and write file - save as location 8 54
PHP AJAX JSON 2 75
Jquery 10 24
How can I alter this script restrict file types with a suffix of 4 charaters also? 3 27
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, …
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
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…

789 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