简体   繁体   中英

How to restart JS function?

I have a script for "like" button. When I am clicking to button, AJAX sending data to videolike.php

  1. First I am getting videos from database using PHP with limit 10

  2. After this is loading this script...

     <script type="text/javascript"> $(".vidlike").click(function() { var form = $(this).closest(".vidlikform"); $.ajax({ type: 'post', url: "functions/videolike.php", data: form.serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); return false; // avoid to execute the actual submit of the form. }); </script> 

Now I have 10 videos in my HOME page, The script is working fine. Sending data to videolike.php without redirecting...

The problem is this script is working only for first 10 videos, 'its not working for next videos i got from database, redirecting me to videolike.php ...

This is the script I am using for get more data:

<img class="load-more" id="<?php echo @$var['video_id']; ?>" src="img/loader.gif"/>

<script type="text/javascript">
    //Ajax more data load Home page
    $(document).ready(function(){
        $(window).scroll(function(){
            var lastID = $('.load-more').attr('id');
            if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
                $.ajax({
                    type:'POST',
                    url:'functions/getData.php',
                    data:'id='+lastID,
                    beforeSend:function(html){
                        $('.load-more').show();
                    },
                    success:function(html){
                        $('.load-more').remove();
                        $('#main').append(html);
                    }
                });
            }
        });
    });

    </script>

You will want to use a delegated event handler.

This will attach a single listener, and compares the clicked target against the selector, in this case .vidlike .

This will work even if you modify the DOM by adding more results.

$('body').on("click", ".vidlike", function() {
     var form = $(this).closest(".vidlikform");

     $.ajax({
          type: 'post',
          url: "functions/videolike.php",
          data: form.serialize(), // serializes the form's elements.
          success: function(data)
          {
              alert(data); // show response from the php script.
          } 
     });
     return false; // avoid to execute the actual submit of the form.
});

See the docs for .on() for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM