Search code examples
javascriptajax

Do something when a AJAX load has completed successfully


I am totally gutted, I just lost a whole load of code and trying in a rush to get it sorted. I have got most done but I have a section that when a button is clicked it loads a page and displays it with AJAX. All works fine but I want to add a loading gif when it starts and then hide it only when its complete. I keep getting errors and I know its easily possible but keep getting it wrong.

I have just added this to end, is it correct? It says it checks for all completed AJAX functions?

$(document).ajaxStop(function() {
  //alert("LOADED");
  $('#loader').hide();
}); 

The code is

$(document).ready(function(){
    $(".mainstuff button").click(function(){
    $('#loader').show();
        status = $(this).attr("data-name");
        var new_url = "demo_text.php?job_id="+status;
        //alert(status);
        $("#div1").load(new_url);

// I want to hide when its loaded successfully here 
        $('#loader').hide();
    });
}); 

I know its something like

.load(url, function(response, status, xhr) {
            if (status == "error") {
                var msg = "Sorry but there was an error: ";
                $("#content").html(msg + xhr.status + " " + xhr.statusText);
            }

But I keep getting errors, any help would be great thanks


Solution

  • According to the load documentation, you would do it like this:

    $(document).ready(function(){
        $(".mainstuff button").click(function(){
        $('#loader').show();
            status = $(this).attr("data-name");
            var new_url = "demo_text.php?job_id="+status;
            $("#div1").load(new_url, function() {
                // Callback executed once the load has been performed
                $('#loader').hide();
            });        
        });
    });