peace_love
peace_love

Reputation: 6471

How can I reset an Ajax success function?

   $(document).on("click", ".example", function (event) {
        alert("test");
        var id = 1;
        $.ajax({
            url: "update.php",
            data: {
                id: id,
            },
            type: "POST",
            success: function (data) {
                $("#result").html(data); 
            }
        }) 
    });

If I remove this line...

 success: function (data) {
   $("#result").html(data); 
 }

... then "test" is alerted on every click only once.

But with this line every time I click on my .example button, "test" is alerted on more time.

So this means:

... and so on.

I think it is caused because the .example button was also created by Ajax before.

So is there a possibility to reset somehow the success function?

Upvotes: 0

Views: 4825

Answers (3)

Nagaraju
Nagaraju

Reputation: 1875

this should help

   $(document).unbind("click").on("click", ".example", function (event) {
          //your code
    });

Unbind it so that it gets attached only once

From api.jQuery Event handlers attached with .bind() can be removed with .unbind(). In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements:

As suggested in comments by charlietfl use off as unbind is deprecated.

Upvotes: 2

Rohan Kumar
Rohan Kumar

Reputation: 40639

Because your script is initialised again and again on every success callacks, so just off() the event before using on() like,

$(document).off("click", ".example").on("click", ".example", function (event) {
    alert("test");
    var id = 1;
    $.ajax({
        url: "update.php",
        data: {
            id: id,
        },
        type: "POST",
        success: function (data) {
            $("#result").html(data); 
        }
    }) 
});

Upvotes: 2

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

Remove/Unbind the old listener and add new like:

$(document).on("click", ".example", function (event) {

change it to:

$(document).off("click", ".example").on("click", ".example", function (event) {

and try again.

Explanation: The issue is your script is initialised again and again on every success callacks. So $(documeon("click", ".example", function (event) {nt).off("click", ".example") will unbind all listener and on("click", ".example", function (event) { add new one.

Upvotes: 2

Related Questions