2

When I call an api that returns a random quote in json format (a title and content), I receive the json just fine :

ajax({ url: 'quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', type: 'json' }, 
function(data) {
console.log(( JSON.stringify( data ) ));
console.log(data.content);

console.log(( JSON.stringify( data ) )); 

outputs :

[{
   "ID":1562,
   "title":"Michael Bierut",
   "content":"Most of the mediocre design today comes from designers who are faithfully doing as they were taught in school: they worship at the altar of the visual.\n",
   "link":"http:\/\/quotesondesign.com\/michael-bierut-3\/",
   "custom_meta":{"Source":"article"}
}]

But console.log(data.content); outputs : none.

Rayon
  • 36,219
  • 4
  • 49
  • 76
Delano zuurman
  • 234
  • 2
  • 11
  • 1
    The root JSON value doesn't have a `"content"` property to match `data.content`. It appears `data` is an Array – `console.log(data[0].content)`, etc. ([Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json)) – Jonathan Lonowski Apr 21 '16 at 04:46
  • @RayonDabre It isn't clear that this is jQuery. Despite some similarities, the arguments don't appear to be compatible with `jQuery.ajax()`. – Jonathan Lonowski Apr 21 '16 at 04:55
  • @JonathanLonowski, True! – Rayon Apr 21 '16 at 04:56

3 Answers3

2

try console.log(data[0].content);

or hor
  • 723
  • 3
  • 11
1

I believe the issue is that you are stringifying instead of parsing

console.log(JSON.parse(data));

Edit: The example on the question has some other problems as well. Here is a correctly formatted ajax request:

$.ajax({
  type: 'GET',
  dataType: 'json',
  url: 'URL_HERE',
  success: function(data) {
    console.log(data.content);
  }  
});

and a working example https://jsfiddle.net/1fjqgajk/8/

Daric
  • 440
  • 1
  • 4
  • 12
0
$.ajax({url:"quotesondesign.com/wp-json/posts?  filter[orderby]=rand&filter[posts_per_page]=1",type:'POST',dataType="json",success: function(data){
// if you dont wanto to use dataType use eval;
 //var jsonObj=eval(data)

}});
Tosif
  • 36
  • 5