Coder53
Coder53

Reputation: 23

wait for callback of getJSON finish in jquery

I has something like this:

<div id="content"></div>

and JS:

function getData(id) {
    $.getJSON('url/to/jsondata',{id: id}, function(data) {
         /** append some data to div#content  **/
         $('#content').data('key', 'value');
     });

then I want to get data of #content in script:

$(document).ready(function() {
    getData(1); // run getData with some id
    console.log($('#content').data('key'));
});

Problem is console.log not run after callback of getJSON finish, so i get a undefined value in log. Which is right way to make it work? Thank!

Upvotes: 2

Views: 10900

Answers (3)

adeneo
adeneo

Reputation: 318212

Return the deffered object from the ajax function and use the always, done or fail methods on it:

function getData(id) {
    return $.getJSON('url/to/jsondata',{id: id}, function(data) { //return this
         $('#content').data('key', data);
     });
}

$(document).ready(function() {
    getData('content').always(function() { //is returned as deffered object
        console.log($('#content').data('key')); //runs when ajax completed
    });
});​

Upvotes: 2

Mario S
Mario S

Reputation: 11945

You should put the log-call in the callback-function like this:

function getData(id) {
    $.getJSON('url/to/jsondata',{id: id}, function(data) {
         /** append some data to div#content  **/
         $('#content').data('key', 'value');

         console.log($('#content').data('key'));
     });

Upvotes: -1

TheZ
TheZ

Reputation: 3732

You have already defined the callback in your getJSON call. To get the results put your console.log code near in the same function as the /** append some data to div#content **/ comment.

Here's the jQuery documentation for getJSON so you can see which is the correct argument and how you can lay it out: http://api.jquery.com/jQuery.getJSON/

Upvotes: 2

Related Questions