0

I am trying to get a file content using jQuery .get() method like below

var news;
$.get('news.txt', function (dat) {
   news = dat;
   if ($('#removeN').is(':checked')) {
       news = "";
   }
   alert(news) // Displaying exact result;               
});
alert(news) // Displaying undefined..; Why?

Someone please clarify my doubt.

4
  • 4
    Welcome to the wonderful world of async! You can't do that. Commented Aug 1, 2012 at 14:02
  • 1
    make a synchronous call instead ? Commented Aug 1, 2012 at 14:02
  • There are so many dublicates out here... Can someone find one proper? Commented Aug 1, 2012 at 14:06
  • A dublicate is when Skrillex steals someone's material. Commented Aug 1, 2012 at 14:44

4 Answers 4

4

AJAX is asynchronous.

Your last line runs before you get a response from the server.

Sign up to request clarification or add additional context in comments.

Comments

3
var news;
$.get('news.txt', function (dat) {
   news = dat;
   if ($('#removeN').is(':checked')) {
       news = "";
   }
   alert(news) // BEFORE THIS!         
});
alert(news) // THIS EXECUTES

use this instead if you want to do something with the news:

$.get('news.txt', function (dat) {
   news = dat;
   if ($('#removeN').is(':checked')) {
       news = "";
   }
   doSomething(news) // Displaying exact result;               
});

var doSomething = function(data) {
    alert(data);
}

Comments

2

You should also be able to separate out concerns..

var news;
$.get('news.txt', function (dat) {
   //process news       
}).done(function(dat){
   //display news, or maybe more processing related to this particular function block
   alert(news);
}).fail(function(){
   //oops, something happened in attempting to get the news.
   alert("failed to get the news");
}).always(function(){
   //this eventually gets called regardless of outcome
});

etc.

Comments

1

The second parameter to $.get is a callback. Essentially what $.get is doing is setting up an event handler to the content loaded event, and saying "here's the function I want to run when this event is fired." Like others have said, it hasn't fired that event yet, so the code rambles through and finds your uninitialized variable.

Comments

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.