0

I am reading about Ajax Events from the jQuery docs.

My jQuery code with some HTML:

<p style="display:none">Loading...</p>
<div></div>

$(document).ready(function() {

    $("p")
    .ajaxStart(function(){
        $(this).show();
    })
    .ajaxStop(function(){
        $(this).hide();
    });


    $.ajax({

        url :    'http://localhost/xampp/web_development/new_study_2014/my_files/test.php',
        data :   {id : 123},
        type :    "GET",
        dataType : "html",
        success: function(response) {
            $("div").hide().html(response).fadeIn(1500);
        },
        error: function(xhr, status, errorThrown) {
            console.log( xhr + status + errorThrown );
        },
        complete: function() {
            console.log(  );
        }
    });

});

The PHP:

<?php
sleep(1);
echo "<p> his name is jack</p>";
?>

I wanted the paragraph that says Loading... to display when the ajax request starts and hides when it is finished. As described in the jQuery docs. Yet it does none of the two and displays "his name is jack" from the php page. What am I doing wrong?

1
  • 2
    From the jQuery documentation: As of jQuery 1.8, the .ajaxStart() method should only be attached to document. Commented Jul 23, 2015 at 0:55

1 Answer 1

2

The target of the ajaxStart event is the document, not a particular element, so using $(this) in the handler won't work. Change it to select the specific element.

jQuery:

$(document).ajaxStart(function() {
    $("#loading").show();
});
$(document).ajaxStop(function() {
    $("#loading").hide();
});

HTML:

<p id="loading" style="display: none;">Loading...</p>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks did it as you specified but still same output as the above question.
If you put alert() into the ajaxStart and ajaxStop functions, do they fire?
Hmm that's weird. It does alert() for both start and stop but for some reason the show and hide of the paragraph does not work. The code I posted is pretty straightforward.
It works on jsfiddle but not locally. Locally it now shows Loading... for like a microsecond and then disappears.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.