rpsep2
rpsep2

Reputation: 3111

ajax json request, how to display result?

I'm making a call via ajax to an api. whats the easiest way to display the result? if i alert the result i simply get [object object], if I try to alert the result with an item I know is in the returned json (results.title, for example) I just get an 'undefined' error.

the code im using looks like:

$.ajax({
    url: 'http://API-LINK-format=json',
    dataType: 'json',
    success: function(results) {
    alert(results.title);
    alert(results)
    }
})

I tried to parseJSOn but I get an error with that to, unexpected token o.

any help appreciated! thanks

the api returns something like:

{"request":
    {
     "format":"json","method":"theMethod","id":"theID"},
     "time":"0.00863",
     "job":{"types":{"type":["Permanent"]},
     "email":"EMAIL",
     "title":"theTitle"
     }
}

only more nested, longer etc

EDIT::

using:

alert(results.request.title);

I still got an undefined alert. I ran an each loop, turns out I'm somehow getting 3 results? I run this code:

$.ajax({
    url: 'http://API-LINK-format=json',
    dataType: 'json',
    success: function(results) {
        $.each(results, function(i, result){
             alert(result.title)
        }
    }
})

and it alerts 3 times, first 2 as undefined, then 3rd gives me what I need.. but like I say I know the api is returning a json like the above, just more items

Upvotes: 1

Views: 1238

Answers (2)

steo
steo

Reputation: 4656

I guess is an asynchronous problem , try with :

var req = function(){

return $.ajax({
         url: 'http://API-LINK-format=json',
         dataType: 'json',
         success: function(results) {
          console.log('success');
         }
       })
});

req().done(function(data) {
 //do something with data
});

Maybe I'm guessing wrong, but just try this out.

http://api.jquery.com/deferred.done/

Upvotes: 0

wirey00
wirey00

Reputation: 33661

You would need

requests.job.title

Here's your actual structure if you formatted it

{ // <-- this is your requests object
    "request": { // -- what you want isn't in here -- this is the first element in the each loop
        "format": "json",
        "method": "theMethod",
        "id": "theID"
    },
    "time": "0.00863", // <-- it isn't here either -- this is the second element in the each loop
    "job": { // it's here - so you want request.job -- this is the third
        "types": {
            "type": ["Permanent"]
        },
        "email": "EMAIL",
        "title": "theTitle" // to get this it's request.job.title
    }
}

FIDDLE

If you are using Chrome - it makes it very easy to inspect your object by doing a console.log and checking the console

Upvotes: 2

Related Questions