0

Can anyone tell me why the below gives me an empty string? When I console.log(contentArray) in the $.get() callback function it shows the data but when I try to do it where it is in the code below, the result is empty.

sectionArray = [];
contentArray = [];
$(function () {
    if (index == 1) {
        $('menu:eq(' + (section - 1) + ') li a').each(function () {
            sectionArray.push($(this).attr('href'));
        });

        var len = sectionArray.length;

        for (var i = 0; i < len; i++) {
            href2 = sectionArray[i];

            $.get(href2, function (data) {
                string = data.toString();
                contentArray.push(string);
            });
        }
        content = contentArray.toString();
        console.log(content);
    }
Psylant
  • 93
  • 1
  • 10

2 Answers2

2

because ajax request ends after you call console.log() try this:

$.get(href2, function(data){
    string = data.toString();
    contentArray.push(string);
    content = contentArray.toString();
    console.log(content);
});

also do ajax request in loop is not best thing to do. that wont work as you want.

UPDATE:

also jQuery has async option set to false and your code should work but will work slow. Synchronous requests may temporarily lock the browser.

UPDATE 2

maybe try something like this(maybe not so good idea :D):

var countRequests = len;
$.get(href2, function(data){
    string = data.toString();
    contentArray.push(string);
    countRequests = countRequests - 1;
    if (countRequests == 0) {
        content = contentArray.toString();
        console.log(content);
        // or create callback
    }
});
Vytautas
  • 3,509
  • 1
  • 27
  • 43
  • that works, because $.get(href2, function(data){ content = contentArray.push(data); console.log(content); }); works. I tried $.get(href2, function(data){ string = data.toString(); contentArray.push(string); }); content = contentArray.toString(); console.log(content); but that doesn't work – Psylant Mar 29 '12 at 10:47
  • that because `.push()` goes after `console.log()` – Vytautas Mar 29 '12 at 10:54
  • I have to do it in a loop because I need to collect data from multiple pages then drop it into 1 page – Psylant Mar 29 '12 at 10:54
  • @Psylant - I think given answer is appropriate, even though that you want to achieve your functionality then you can achieve by directly dropping content on page rather taking in variable. replace 'contentArray.push(string);' by '$(".somedivision").append(string)' – Hardik Patel Mar 29 '12 at 11:03
  • yeah I know what you mean, I actually had it working that way. But the problem is that I need to get a callback function working after the content is dumped into the page, so for that i need to load the content into the array, then load it into the div then callback print only that div. – Psylant Mar 29 '12 at 11:10
1

The problem is that your $.get() ajax requests are executed asynchronously.

That is, the $.get() function returns immediately without waiting for the response, your entire for loop completes (queueing up multiple ajax requests), then your console.log() occurs at which point the array is still empty. Only after that do any of the ajax success handlers get called, regardless of how fast the ajax responses come back.

EDIT: Here is an answer from another question that shows how to do something after all the ajax calls have completed: https://stackoverflow.com/a/6250103/615754

Community
  • 1
  • 1
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • ahhh ok that makes sense, so if I put say an if statement in there to execute once i>len that should execute after the for loop has finished? – Psylant Mar 29 '12 at 11:02
  • No, the for loop will definitely finish before any of the success callbacks run so an if statement won't work unless you move your console.log() into the callback and maintain a count of how many responses you've received. Take a look at the answer I linked to, and read up on the $.when () method. – nnnnnn Mar 29 '12 at 11:24