1

I've got a mysterious problem ... I try to take a part of an external page and put it in a variable. Here is the code :

$.get(url, function( data ) {
     title = $(data).find('#layout-column_column-1 .journal-content-article').html();
}, 'html');
alert(title);

Using the javascript console on my browser (which is Chrome but that's the same on others), when I execute this code once, the alert(title) returns "undefined". Then if I run it again (or just the line alert(title)), I've got the result I expected.

Anyone has an idea ? :)

EDIT : sorry, the code I gave was not complete :

var a = $('a[target="_faq"]');
a.each( function() {
    [...]
    var title;
    $.get('url', function( data ) {
        title = $(data).find('#layout-column_column-1 .journal-content-article').html();
    }, 'html');
    $(this).attr('title', title);
}
Ju_Der
  • 57
  • 7

3 Answers3

2

That is what asynchronous means.

$.get(url, function( data ) {
     title = $(data).find('#layout-column_column-1 .journal-content-article').html();
     alert(title);
}, 'html');

That means sending the request (or rather receiving the response) is taken out of the normal execution flow.

Heavily recommending @Felix's great answer: How do I return the response from an asynchronous call?.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

It is because the $.get() sents an ajax request, which is processed asynchronously, which means that once the request is sent the next script will get executed without waiting for the response.

It is working in the second attempt because, the title is a global variable here. When the first request is sent the alert displays undefined and then when the response comes back updates the value of the title variable to the returned value. When the second attempt is made the request is sent again but when the alert is executed the title is already updated with the value from the first request so it gets displayed

In any async processing, the values returned by the async activity must be handled by a callback method.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

The get method (as well as ajax and post) is executed in "another thread" (between quotations because javascript isn't multithreaded).

The get method is called, then the request is started to execute, and the code proceeds to your alert(title), which is outside the asynchronous method and thus executed before the first one is ended.

Put your alert inside the get. Problem solved

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93