Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery events fire more than once

Tags:

jquery

ajax

first of all, I did my home work, I already searched Google and used evt.stopPropagation(); and unbind method, but not fixing my problem... .

Here is my case:

Imagine I have a left sidebdar with some linkes, on click of each link the middle col will be reloaded by ajax with some code like this:

<script>
$('.leftsidebar a').on('click', function(){
    var page = $(this).attr('class')
    $('#middleCol').load('loader.php?page='+ page);
});
</script>

So on each click on the left side bar a tag, the middle col will loads that a tag class.php, it's just fine.

now in the pages that I'm loading in the middle col, at the end of the page I have some javascripts,, for example if it loads by loader.php?page=test in test page I have some new jQuery lines, an example:

<script>
$('#blah').on('click', function(){
    $.ajax({
        type: 'POST',
        url: 'server.php',
        success: function(response){
            //blah  
        }   
    }); 
});
</script>

Now the problem is, when the first time, I load test page by clicking on leftside bar a tag, it works just fine, on click of #blah only 1 request will be sent to server.php, but when I click on another a from leftsidebar, then come back to the test, now if I click on blah, the ajax request will be sent twice to the server.php, and so on..., if I try it again, request will be sent for 3 times!

How can I prevent such behavior? what is the solution?

I appreciate helps.

like image 478
behz4d Avatar asked Jan 31 '26 21:01

behz4d


2 Answers

You could do that too if no more than one click handler is bounded to this element:

$('#blah').off('click').on('click', function(){...});

But better would be to not include useless/redundant code

like image 99
A. Wolff Avatar answered Feb 03 '26 12:02

A. Wolff


A fairly simple solution would be to bind data to #blah to determine whether that click event is already bound to prevent it from binding again.

$("#blah:not([data-bound])").on('click', function () {
    /* your code */
});
//not using .data to ensure attribute string set for selector use.
$("#blah").attr('data-bound', 'bound');
like image 31
Explosion Pills Avatar answered Feb 03 '26 13:02

Explosion Pills