jack
jack

Reputation: 15

JQuery load() make Jquery functions fires multiple times

This is my code. It loads the pages content without refresh.

The problem is when I click on button handled by jQuery and ajax it fires as many times as I load the pages.

For e.g. If loaded 2 pages, jQuery will fire twice

If I loaded 4 pages, jQuery will load 4 times.

 <script>
        $(document).ready(function(){
            //set trigger and container

            var trigger = $('#nav ul li a'),
                container = $('#container');
            //do on click


            trigger.on('click', function(e){
                /***********/
                 e.preventDefault();

               /* reload content without refresh */
                //set loading img
                $('#container').append('<div id = "loading">WAIT...  <img src = "img/ajax-loader-small.gif" alt="Currently loading"   /></div>');
                //change img location to center
                $("#loading").css({"position": "absolute", "left": "50%", "top": "50%"});
                //get the  trigger to reload the contents
                var $this = $(this),
                    target = $this.data('target');

                container.load(target + '.php');

              //  return false;
                $(trigger).die('click');
            });
        });

This script fires as many times as I load the page through load() function which mean same post will be inserted many times into the database

<script>

    $(document).ready(function(){


    $(document).on("click",".fa-pinterest-square",function(e) {


        var form = $(this).find('form'); //Since the form is child to <i>

        $.ajax({
            url: "includes/widgets/add_pains.php",
            type: "POST",
            data: form.serialize(),
            success: function(data) {
                alert(data);

            }
        });

    });
    });

</script>

How can I fix this issue?

Upvotes: 1

Views: 1279

Answers (3)

jack
jack

Reputation: 15

I fixed the problem by inserting the script in index.php, maybe it was called several time due to include the home page.

Upvotes: 0

Affan
Affan

Reputation: 1140

Please use this it will solve your problem

    trigger.unbind().click(function()

         //code 
   });

Upvotes: 1

J.C. Fong
J.C. Fong

Reputation: 546

This happened because you didn't clear the event listener each time you load the script and the event listener stacked on each other caused trigger multiple times.

trigger.off('click').on('click', function(){....})

The .off() method removes event handlers that were attached with .on().

Upvotes: 3

Related Questions