0

This seems really bizarre...

I have some JSON...

{"firstName":"David","lastName":"Smith","email":null,"id":0}

But when I try to parse it and use it with...

<script>
    $(document).ready(function() {
        var json = $.getJSON('userManagement/getUser');
        $("p").text(json.firstName);
    });
</script>

This is the user management view

Users : <p></p>

Nothing appears, but if I just do $("p").text(json); it tells me it's an object and I can see the JSON is correct in firebug, any ideas?

David
  • 19,577
  • 28
  • 108
  • 128

4 Answers4

7

Try:

<script>
    $(document).ready(function() {
        $.getJSON('userManagement/getUser',function(json){
            $("p").text(json.firstName);
        });            
    });
</script>

You have to work with the json variable after the AJAX request has completed.

Learn more here about AJAX JSON Requests: http://api.jquery.com/jQuery.getJSON/

Learn more here about general AJAX Requests: http://api.jquery.com/jQuery.ajax/

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
2

The $.getJSON() function is just a wrapper around an AJAX call; it doesn't return the JSON that it gets as a result of the AJAX call, but instead returns a jqXHR object (thanks to Mathletics for clarifying this).

You'll need to supply a callback function to do whatever processing of the JSON you need.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • It does not return a jQuery deferred, but rather a jqXHR: http://api.jquery.com/Types/#jqXHR – Evan Davis Apr 17 '12 at 17:48
  • @Mathletics although the `jqXHR` object implements the `promise` interface, so it's much the same thing. – Alnitak Apr 17 '12 at 17:49
  • @Mathletics I went to check the docs after posting my answer because I wasn't entirely sure. Thanks for letting me know, though - updated my answer. – Anthony Grist Apr 17 '12 at 17:51
2

$.getJSON() is asynchronous - it doesn't return the JSON.

You need to supply a callback function, either using:

$.getJSON(url, callback);

or

var jqxhr = $.getJSON(url);
jqxhr.done(success_callback); // will be passed the JSON
jqxhr.fail(error_callback);   // will be called if there's an error

the latter is more flexible, as you can also register error callbacks, which the raw $.getJSON method doesn't support.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Regarding to your question, take a look on two similar threads where @iambriansreed participated: [First](http://stackoverflow.com/q/10572350/601179), [Second](http://stackoverflow.com/q/10213620/601179). Should I continue? – gdoron Jun 03 '12 at 08:09
1

You need to use a callback-function, since you retrieve your data asynchronously.

The moment you call $("p").text(json.firstName); the JSON is not loaded yet.

Thats why you have to use:

$.getJSON('userManagement/getUser',function(json){...your code here... }<-callback

Christoph
  • 50,121
  • 21
  • 99
  • 128