Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery prevent links working whilst ajax is loading

I have a firework detonation system which uses JQuery to connect to a PHP script via AJAX to detonate the fireworks. The only problem is that if you click one launch button straight after another, there is a possibility of setting off more fireworks than you want.

I need a way to disable all other links on the page until the ajax has finished and received a response. I have tried:

//Prevent clicks
$("body").find("a").click(function (e) { e.preventDefault(); });
//Re-enable clickable links
$("body").find("a").unbind("click");

My current ajax script is:

$(document).ready(function() {
$(".button").on("click",function() {
    //Disable all other links
    $.ajax({
        type: "POST",
        url: "launch.php",
        data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
        success: function(e) {
            //Re-enable other links once ajax is complete
        }
    });
    return false;
});
});

What would be even better is, if the buttons were to grey out whilst waiting for the response. I have a demo script at http://joshblease.co.uk/firework/

like image 752
Blease Avatar asked Sep 15 '25 23:09

Blease


1 Answers

One way using a variable disabled

$(document).ready(function() {
var disabled = false;
$('a').css('opacity','0.4');
$(".button").on("click",function() {
    //Disable all other links
    disabled = true;
    $.ajax({
        type: "POST",
        url: "launch.php",
        data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
        success: function(e) {
            //Re-enable other links once ajax is complete
            disabled = false;
            $('a').css('opacity','1');
        }
    });
    return false;
});
});

$('a').click(function(event){
    if(disabled)
        event.preventDefault();
});

Update

Changed link opacity for a disabled effect.

like image 158
Trevor Avatar answered Sep 18 '25 19:09

Trevor