Bidoubiwa
Bidoubiwa

Reputation: 960

jQuery action when .load() is done

I am trying to have an action that starts when my load() request is done, but the alert never shows up. The load() request works since I can see the content of mypage.html in my .haha div. This is the really simple code:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Hello
<div class="haha"></div>

<script type="text/javascript">
    $(document).ready(function(){
        $('.haha').load('mypage.html', function(xhr) {
            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
                alert('TEST TEST'); 
            }
            alert('TEST TEST'); 
        });
    });
</script>

None of the alerts shows up.

EDIT : In my console i have this :

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
FAToolbar.js:1 Uncaught TypeError: $.cookie is not a function

Upvotes: 1

Views: 1296

Answers (2)

yunnysunny
yunnysunny

Reputation: 303

first,the function load 's callback parameter is only called after request has completed, so you don't have to check xhr.readyState == 4.
second,you load a html via the function load,and i guess that the page mypage.html include some javascript code , and some code call the function $.cookie which is not include in the page.So the error print in you console product by you js code from the page mypage.html.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

If you check the documentation for load() you'll see that the xhr object is the third parameter passed to the callback function. Your code is most likely generating a syntax error in trying to access properties of the returned string which don't exist, which is stopping further execution. Try this:

$('.haha').load('mypage.html', function(response, status, xhr) { // note the extra params
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
        alert('TEST TEST'); 
    }
    alert('TEST TEST'); 
});

Upvotes: 4

Related Questions