1

I'm practicing Ajax calls and am having issues accessing the returned JSON data.

I have the following code below

$('button').on('click', function() { 
  $.ajax({
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
    success: function(data) {
      console.log(data);
    },
    error: function() {
      console.log('error occured');
    },
    cache: false
  });
});

which outputs

[
{
"ID": 1127,
"title": "Paul Rand",
"content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear.  </p>\n",
"link": "https://quotesondesign.com/paul-rand-7/"
}
]

I'm just trying to output the content and link properties of my JSON object. I've tried the following:

$('.message').html(JSON.stringify(data));

which outputs

[{"ID":2294,"title":"Josh Collinsworth","content":"
You do not need to have a great idea before you can begin working; you need to begin working before you can have a great idea.

\n","link":"https://quotesondesign.com/josh-collinsworth-3/"}]

I'm trying to look for the standard way to manipulate JSON data, thanks for all the help!

miken32
  • 42,008
  • 16
  • 111
  • 154
hello world
  • 1,727
  • 6
  • 21
  • 37

1 Answers1

4

As the name suggests, stringify turns the JSON into a string. JSON is native JavaScript, and based on your sample data:

[
    {
        "ID": 1127,
        "title": "Paul Rand",
        "content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear.  </p>\n",
        "link": "https://quotesondesign.com/paul-rand-7/"
    }
]

you get back an array (in square brackets) of objects (in curly braces.) In this case it's just one object in the array, so you access the first object in the array with data[0] and then get its content property:

$('.message').html(data[0].content);
miken32
  • 42,008
  • 16
  • 111
  • 154