I had this working when calling the API for a random movie quote generator on Mashape.com. My initial intention was to build an app that would generate bible quotes. I'm using this marketplace page https://market.mashape.com/acg/uncovered-treasure#random. I'm not getting any errors in the console, just this:
getNewQuote()
arguments: null
caller: null
length: 0
name: "getNewQuote"
prototype: Object { … }
__proto__: function ()
quote1.js:5:9
OPTIONSXHR
https://uncovered-treasure-v1.p.mashape.com/random
[HTTP/1.1 200 OK 170ms]
GETXHR
https://uncovered-treasure-v1.p.mashape.com/random
[HTTP/1.1 200 OK 178ms]
undefined
quote1.js:13:11
undefined
I can't figure out why I'm not retrieving the data (text, context) I'm calling in the function displayQuote. What am I doing wrong?
Jquery:
$(document).ready(function() {
//function to call a quote and bible verse
function getNewQuote() {
console.log(getNewQuote);
$.ajax({
type: "GET",
url: "https://uncovered-treasure-v1.p.mashape.com/random",
data: {},
dataType: "json",
success: function displayQuote(data) {
//display the quote
$("#quote").html(data.text);
console.log(data.text);
//display the book the bible verse is being taken from
$("#author").html("-" + data.context);
console.log(data.context);
//commented the Tweet button out until I can get the quotes to work
// function tweetQuote() {
// var twitterURL =
// 'https://twitter.com/intent/tweet?hashtags=quotes,freeCodeCamp&related=freecodecamp&text="';
// var quote = $("#quote").html();
// var author = $("#author").html();
// twitterURL += text + " " + context;
// $("#tweet").attr("href", twitterURL);
// }
},
//error message to display if the call does not work
error: function() {
prompt("Try again, God is on your side.");
},
//Mashape authorization and key
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader(
"X-Mashape-Key",
"[API-KEY]"
);
xhr.setRequestHeader("Accept", "application/json");
}
});
}
//call a new quote each time the button is clicked
$("#get-quote").on("click", getNewQuote());
// console.log(getNewQuote);
})
That is because you are trying to access the
data.contextwhereas the API returns in the formatdata.results.The
resultsis an array which has records on each index so you need to replace thedata.contextanddata.textstatements in your ajaxsuccessfunction withand
respectively
and if there are multiple records returned via API then you need to use the
for inloop like this