Jump to content

Recommended Posts

I have two pieces of code, one loads more comments and the other sends feedback. Both of the calls use AJAX and work separately but they don't work together.

The code I've got is:
<script type="text/javascript">              var comments_offset=<?php echo $more ?>;              function comments_load() {                $.ajax({                  url: "/comments.php?pid=<?php echo $id ?>&offset="+comments_offset+"&t="+Math.random(),                  success: function(data){                    if( data.substring( 0,5 )!="failed" ) {                      bits=data.split( "==DSPLIT==" );                      $(bits[1]).insertBefore( "#comments-control" );                      comments _offset=bits[0];                      if( comments_offset==0 ) { $("#comments-control").hide(); }                    }                  }                });              }            </script>            <div id="comments-control" <?php if( !$more ) { ?> style="display: none;"<?php } ?>>              <br /><a class="input_button" onclick="reviews_load();" href="javascript:void(0);" style="padding: 10px; height: auto; background-color: #000; border: 1px solid white; color: #fff;">Laod more comments </a>            </div>
Which loads more comments
And this which registers feedback for the comments. It works great for the first ten comments but when I use the other code to load more it then stops working
<script type="text/javascript">$(".rate-yes").click(function(e) {    // "this" here corresponds to the button that was clicked    var self = this;      $.ajax({        async: false,        type: "POST",url: "/rate.php?rate=good&id=" + $(self).val(),         data: $(self).serialize(), // self instead of the class        success: function(data) {            $('#helpful' + $(self).val()).fadeOut("fast", function() {                $(this).before("<div class='rate'>Was this comment helpful?   <span style='color: #33cc33;'>✓ Thank you for your feedback</span></div>");            });        }    });});             $(".rate-no").click(function(e) {    // "this" here corresponds to the button that was clicked    var self = this;      $.ajax({        async: false,        type: "POST",url: "/rate.php?rate=bad&id=" + $(self).val(),         data: $(self).serialize(), // self instead of the class        success: function(data) {            $('#helpful' + $(self).val()).fadeOut("fast", function() {                $(this).before("<div class='rate'>Was this comment helpful?   <span style='color: #33cc33;'>✓ Thank you for your feedback</span></div>");            });        }    });});</script>
I've tried to use $(".rate-yes").on("click",function(e) { and $(".rate-no").on("click",function(e) { instead but that doesn't work either
Edited by unplugged_web
Link to post
Share on other sites

When you generate new HTML with Javascript or jQuery, you need to bind the events to the newly created elements.

 

I assume bits[1] is HTML code. So what you would do is bind the event to that.

var newElement = $(bits[1]);newElement.click(function() {    // event code goes in here});newElement.insertBefore( "#comments-control" );
Link to post
Share on other sites

Using .on() means it should work on current elements and newly created elements that match selector, you don't have rebind to newly created elements.

 

Just make sure you are using current jquery version, as this was done using .live(), then delegate() on older jquery versions, which were then superseded by .on().

Edited by dsonesuk
Link to post
Share on other sites

IF you have the latest jquery version you should be using .on() it works exactly the same as newElements example.

 

jQuery 1.3+ you would be using live().
jQuery 1.4.3+ you would be using .delegate()

jQuery 1.7 to current version you would use .on()

Link to post
Share on other sites

 

When you generate new HTML with Javascript or jQuery, you need to bind the events to the newly created elements.

 

I assume bits[1] is HTML code. So what you would do is bind the event to that.

var newElement = $(bits[1]);newElement.click(function() {    // event code goes in here});newElement.insertBefore( "#comments-control" );

I tried to use it like this:

<script type="text/javascript">var newElement = $(bits[1]);newElement.click(function() {$(".rate-yes").click(function(e) {    // "this" here corresponds to the button that was clicked    var self = this;      $.ajax({        async: false,        type: "POST",url: "rate.php?rate=good&id=" + $(self).val(),         data: $(self).serialize(), // self instead of the class        success: function(data) {            $('#helpful' + $(self).val()).fadeOut("fast", function() {                $(this).before("<div class='rate'>Was this comment helpful?   <span style='color: #33cc33;'>✓ Thank you for your feedback</span></div>");            });        }    });});             $(".rate-no").click(function(e) {    // "this" here corresponds to the button that was clicked    var self = this;      $.ajax({        async: false,        type: "POST",url: "rate?rate=bad&id=" + $(self).val(),         data: $(self).serialize(), // self instead of the class        success: function(data) {            $('#helpful' + $(self).val()).fadeOut("fast", function() {                $(this).before("<div class='rate'>Was this comment helpful?   <span style='color: #33cc33;'>✓ Thank you for your feedback</span></div>");            });        }    });});});newElement.insertBefore( "#comments-control" );</script>

but then none of it worked. Have I done something wrong?

Link to post
Share on other sites

Where is this code placed? as it is now it should be placed BELOW (bottom of page before </body> would be ideal place) any element using 'rate-yes' or 'rate-no' classes, why? because it won't be able to apply click event function to an element using these classes unless they have been rendered first. IF this code is placed above or linked to in <head>..</head> you should be using jquery onload equivalent code as in

 

$(document).ready(function(){

 

});

 

or

 

$(function(){

 

 

});

 

The newElements code if you want to go that way? should be placed BEFORE

 

$(bits[1]).insertBefore( "#comments-control" );

 

as shown in Ingolme example.in first section of code in post #1

Link to post
Share on other sites

Essentially what I've got is a page of comments. Only ten of them are loaded. People can click to say if a comment was helpful or not. This works okay but after more comments are loaded (which are being loaded by using the code below) the code to give feedback stops working.

All of the comments are being loaded dynamically so I've given the button a class rather than an id.

The code to count the feedback in below where all of the comments are but all except the first ten comments are loaded but the user doing something after the page has loaded

<script type="text/javascript">              var comments_offset=<?php echo $more ?>;              function comments_load() {                $.ajax({                  url: "/more-comments.php?pid=<?php echo $id ?>&offset="+ comments_offset+"&t="+Math.random(),                  success: function(data){                    if( data.substring( 0,5 )!="failed" ) {                      bits=data.split( "==DSPLIT==" );                      $(bits[1]).insertBefore( "#comments-control" );                      comments_offset=bits[0];                      if( reviews_offset==0 ) { $("#comments-control").hide(); }                    }                  }                });              }            </script>
Link to post
Share on other sites

member 'thehappyappy' in post#4 seems to have asked a question for you? i didn't noticed till jsg queried it.

 

Is it possible to see extra dynamic comments to make sure they are showing the same selector for click, or any other anomalies.

Link to post
Share on other sites

Nah that's not me

You sure about that? Is it just a coincidence that both accounts post from the same IP address in the UK, and the email addresses use the same first name? While it's possible that you're an author currently walking the Cornish coast, it's probably more likely that you work for the company on High Road. What I don't understand is why people lie about these things.
Link to post
Share on other sites

I found this in the jQuery documentation:

http://api.jquery.com/on/

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated events to attach event handlers.

 

New events have to be added when new elements are created.

Link to post
Share on other sites

If you read further you are supposed to use a selector for parent element that is always present, this then allows you to target newly created child elements. In other words NO! you STILL do not have to rebind event coding to newly created elements, and what would be the point of click() and .on() if that was true.You should use code similar to

$( "#parent_element" ).on( "click", ".rate-yes", function(){...carry out specific code});
Edited by dsonesuk
Link to post
Share on other sites
<!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />        <title>Document Title</title>        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>        <script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>        <script type="text/javascript">            $(function() {                $('#parent_bind_only_once').on('click', '.dont_rebind_me', function() {                    alert('you just clicked me, owww!');                    $('#parent_bind_only_once').append('<p class="dont_rebind_me no_rebind_alert">HI i'm newly created content that Ingolme claims i need to rebound with click event, BUT! I haven't, strange that?</p>');                });                $('#parent_bind_only_once').on('click', '.no_rebind_alert', function() {                    alert('damn fool! you clicked without rebinding again and again and again, Brilliant!');                });            });        </script>        <style type="text/css">        </style>    </head>    <body>        <div id="parent_bind_only_once">            <p class="dont_rebind_me">                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.            </p>            <p class="dont_rebind_me">                Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida.            </p>            <p class="dont_rebind_me">                Fusce convallis, mauris imperdiet gravida bibendum, nisl turpis suscipit mauris, sed placerat ipsum urna sed risus. In convallis tellus a mauris.            </p>        </div>    </body></html>

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_on_newel

 

as from http://www.w3schools.com/jquery/default.asp below

Definition and Usage

The on() method attaches one or more event handlers for the selected elements and child elements.

As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods. This method brings a lot of consistency to the API, and we recommend that you use this method, as it simplifies the jQuery code base.

Note: Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script).

Tip: To remove event handlers, use the off() method.

Tip: To attach an event that only runs once and then removes itself, use the one() method.

Syntax

$(selector).on(event,childSelector,data,function,map)
Edited by dsonesuk
Link to post
Share on other sites

You sure about that? Is it just a coincidence that both accounts post from the same IP address in the UK, and the email addresses use the same first name? While it's possible that you're an author currently walking the Cornish coast, it's probably more likely that you work for the company on High Road. What I don't understand is why people lie about these things.

 

Yep coincidence I agree but I can assure you that it's not me, although you're right I used to work for a company in High Road (how did you know that one!!) although I'm no longer in London now

Link to post
Share on other sites

As an admin, I can see your email address. Which is why it is curious to me that both accounts use an email address with the same first name, which is a female name not all that common for people of age to work. Especially curious considering that both accounts are marked as male, as if the account owner is specifically trying to conceal who they are. So it wouldn't be all that odd if both of these accounts, which post from the same IP address, are in fact the same woman. Even more strange that the one account popped in here to ask a question from the other account (even using the pronoun "I"), but then that account has not come back to this thread. But you're going to stick with the story that this is all a big coincidence? Do you think I'm buying that? It's not like I would ban you for having multiple accounts, it's not even in the rules. I just don't see any reason to have multiple accounts and I would prefer to merge them.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...