Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery & Scope - $('#elements') outside of a function

Tags:

jquery

scope

I'm a little confused in regards to the scope of things in regards to jQuery and Ajax.

Script start:

 $(document).ready(function () {
        var page = 'index';
        displayContent(page)
});

displayContent contains the ajax call to fetch the text content and shove it into the '#textCotnent' div.

If within the function I alert($('#textContent').text()), it alerts the text fine.

function displayContent(page) {
        $.ajax(//ajax stuff goes here and works fine);
        alert($('#textContent').text()) //alerts the text, hooray.
}

However, if I do the following:

$(document).ready(function () {
        var page = 'index';
        displayContent(page)
        alert($('#textContent').text()); //alerts a blank box, boo.
});

the text is displayed per the ajax call, but the alert pops up null.

I would assume that $('#textContent') would be fine no matter where you called it in the script, but this appears not to be the case.

What don't I understand about jQuery?

like image 499
Thomas Thorogood Avatar asked Sep 14 '26 11:09

Thomas Thorogood


1 Answers

The ajax call is being done asynchronously. You have to wait until a callback function from $.ajax in order to manipulate / access the DOM from the call. I'm surprised the original structure is working. You should use the following structure:

 function displayContent(page) {
   $.ajax(/* ajax parameters */).complete(function() {
     alert($('#textContent').text()) //alerts the text, hooray.
   });
 }

Think of it this way: $.ajax function is returning immediate (in 2-3 ms) and code continues to run. The hit to your server takes ~100ms. Thus, you are jumping the gun and need to wait until the ajax completes before playing around with the results. Does this make sense?

like image 126
ghayes Avatar answered Sep 17 '26 05:09

ghayes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!