2

I am trying to populate $('div').data() through JSON. It works fine with JQuery.parseJSON but not with $.getJSON.

// works as expected
$('div').data('dat', { xmin: '-10', xmax: 40 });
$('div').data('dat', jQuery.parseJSON('{"bbx" : {"xmin" : "-10", "xmax" : "40"}}'));

// doesnt work
$('div').data('dat', $.getJSON("init.php", function(json) {return(json);}));
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
johannes
  • 14,043
  • 5
  • 40
  • 51

4 Answers4

5

you could do:

$.getJSON("init.php", function(json) {
    $('div').data('dat', json);
});
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
3

Probably because getJSON is an async operation. The original statement is now out of scope by the time your success function executes.

Can you not do it this way ?

$.getJSON("init.php", function (json) {
    $('div').data('dat', json);
});
Ravi Y
  • 4,296
  • 2
  • 27
  • 38
3

getJSON is an ajax call which is asyncronous, so the function itself doesn't return anything, it just calls the appropriate callback, so you could do this instead:

$.getJSON("init.php", function(json){
    $('div').data('dat', json);
})

Note: $.get will retrieve the JSON as a string and won't parse it unlike getJSON, so if you want to store the JSON as a string then use $.get. Storing the parsed object will work as well (by using getJSON).

MrCode
  • 63,975
  • 10
  • 90
  • 112
2

You can also store data in array format:

$.getJSON('init.php', function(data) {
    var items = [];

    $.each(data, function(key, val) {
        items.push(val);
    });

    $('div').data('dat', items)
});
palaѕн
  • 72,112
  • 17
  • 116
  • 136