Search code examples
jqueryajaxdouble-submit-problem

jQuery request submitting twice


$("#classesLink").click(function(event) {
    $("#globalUserContent").children().slideUp("normal", function() {
        $.ajax({
            type: "POST",
            url: "classes.php?token="+randString+"",
            success: function (msg) {
                $("#globalUserContent").html(msg);
            },
            error: function (msg) {
                $("#globalUserContent").html(msg);
            }
        });            
    });
    return false;
});

I have the above code and when i click the .classesLink button and check the firebug requests, it shows that it is being submitted twice, is there anything wrong with it?


Solution

  • As noted by @am not I am. $("#globalUserContent") has two childrens so the callback fires twice one for each child, use this:

    $("#classesLink").click(function(event) {
        $.when($("#globalUserContent").children().slideUp("normal"))
         .then(function() {
            $.ajax({
                type: "POST",
                url: "classes.php?token="+randString+"",
                success: function (msg) {
                    $("#globalUserContent").html(msg);
                },
                error: function (msg) {
                    $("#globalUserContent").html(msg);
                }
            });            
        });
        return false;
    });
    

    This will execute the callback- ajax requst, when the slideUp effect is finished, And doesn't hardcode the setTimeout delay in the code.

    If you hardcode 600 in the code, the code could break if the "normal" duration will change some day, or someone changed the slideUp duration effect but didn't change the timeout delay.

    But you can put the duration-delay in a variable so you change it in one place - @am not I am suggestion.

    when docs:

    Description: Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.