P. Fernandez P. Fernandez - 6 months ago 20
jQuery Question

Cannot access individual JSON values / jQuery-Ajax

I am working on a webpage that utilizes an API from some website which generates random quotes. I am attempting to use AJAX/jQuery to access the JSON that is delivered by the API. I have tried a million different things but for the life of me I cannot access the values of the JSON by their ID. I can access the whole JSON. But I can't seem to access the individual values.

This code...

function init() {
var $data = $('#data');

$.ajax({
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type: 'GET',
datatype: 'json',
success: function(data) {
$.each(JSON.parse(data),function(i, quote) {
$data.append('<p class="text-center"> '+quote+ '</p>');
});
},
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization"");
}
});
}
window.onload = init;


This is giving back all of the values, and they are in the correct format. But it gives back all of them. I don't want the last one, and I would like to be able to access each value by ID individually.

{
"quote": "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth.",
"author": "Sherlock Holmes",
"category": "Famous",
}


Above is what the JSON looks like. I only want access to the first two values. When ever I try to access them with something like...

$.ajax({
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous',
type: 'GET',
datatype: 'json',
success: function(data) {
document.write('<p>' + data.quote + '</p>');
},
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "");
}
});


I've tried a million different things but no matter what I do I cannot get access to the values of the JSON by their ID. This is my absolute first time messing with using a web API so I must be missing something. Any help would be appreciated.

Answer

Does something like this work?

...
success: function(data) {
   var items = JSON.parse(data);
   $data.append('<p class="text-center"> '+ items[0].quote + '</p>');
},
...