Der Sep
Der Sep

Reputation:

$.getJson> $.each returns undefined

function getData(d){
Back = new Object();

$.getJSON('../do.php?',
   function(response){    
    if(response.type == 'success'){ 
    Back = { "type" : "success", "content" : "" };
    $.each(response.data, function(data){   
       Back.content +='<div class="article"><h5>'+data.title+'</h5>'
       Back.content +='<div class="article-content">'+data.content+'</div></div>';
      });

    }
    else{
     Back = {"type" : "error" };
    }

    return Back;
  });
}

console.log(getData()); 

is returning undefined! why?

Upvotes: 1

Views: 3157

Answers (2)

Der Sep
Der Sep

Reputation:

Back = new Object();

$.ajax({
    type: "GET",
    async: false,
    url: "../do.php",
    dataType: 'json',
    success: function(response){
        if(response.type == 'success'){ 
            Back = { "type" : "success", "content" : "" };
            $.each(response.data, function(data){           
                        Back.content +='<div class="article"><h5>'+data.title+'</h5><div class="article-image"><img src="'+data.image+'" alt="article_image" /></div>'
                        Back.content +='<div class="article-content">'+data.content+'</div><br class="clear" /></div><!-- /article -->';
                    });

            }
            else{
                Back = {"type" : "error" };
            }

            return Back;
    }});

should it work like this?

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630607

You can't call an asynchronous function in a synchronous way. In your code, this:

function(response){    
    if(response.type == 'success'){ 
    Back = { "type" : "success", "content" : "" };
    $.each(response.data, function(data){   
       Back.content +='<div class="article"><h5>'+data.title+'</h5>'
       Back.content +='<div class="article-content">'+data.content+'</div></div>';
      });

    }
    else{
     Back = {"type" : "error" };
    }    
    return Back;
}

Runs after this: console.log(getData());

The callback (second parameter) in $.getJSON runs once the server returns a response, this doesn't happen instantly.

If you call the logging when it actually runs like this, you will get the expected results:

Back = new Object();
$.getJSON('../do.php?', function(response) {    
  if(response.type == 'success') { 
    Back = { "type" : "success", "content" : "" };
    $.each(response.data, function(data) {   
      Back.content +='<div class="article"><h5>'+data.title+'</h5>';
      Back.content +='<div class="article-content">'+data.content+'</div></div>';
    });
  } else {
    Back = {"type" : "error" };
  }
  console.log(Back); 
});

Upvotes: 2

Related Questions