When Random Quote Machine project is published on the GitHub pages it can’t receive json data. Already tried the $.getJSON and $.ajax(json and jsonp) methods with the same results. On my local machine project works good.
Does anyone know why?
Here is the JS code:
var quote = "";
var author = "";
function getQuote(){
var rand = Math.floor(Math.random()*1000);
var request = "http://quotes.stormconsultancy.co.uk/random.json?callback=respond" + rand;
console.log(request);
$.ajax({
dataType: "jsonp",
url: request,
data: "",
success: function (jsonp) {
console.log(jsonp);
quote = '"' + jsonp.quote + '"';
author = "--" + jsonp.author;
$(".quote").html(quote);
$(".author").html(author);
$(".tweet").attr({
href: 'https://twitter.com/intent/tweet?text=' + encodeURIComponent('"' + quote + '" ' + author)
});
$(".page").css({
backgroundImage: 'url(https://placem.at/things?random=' + Math.floor(Math.random()*1000) + ')'
});
}});
}
$(document).ready(function() {
getQuote();
$("#getQuote").on("click", function() {
getQuote();
});
});
I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.
Thanks, I don’t have experience on this forum.
The JavaScript code above works nice on my local computer and on a CodePen:
But does’t work on the GitHub pages:
https://stepan20000.github.io/Random_Quote_Machine
https://github.com/stepan20000/Random_Quote_Machine
Check your console on the github version.
EDIT: You might want to use https://cors-anywhere.herokuapp.com
1 Like
My git version is git version 2.7.4 if you mean it.
Сan not understand what this link https://cors-anywhere.herokuapp.com is about. Sorry
I meant check your browser console on your website (on github pages)
I made some research. The ajax request is not successful. The process never enter to the success callback function. And json in not received. I don’t know why exactly the same code works on local computer and does’t work on the github pages.
Github pages is loaded over https
and your API request is over http
, which is not allowed.
2 Likes
Thanks a lot. This is the reason. I’ll try to deal with the cross-origin HTTP requests.
I used XMLHttpRequest() as described in https://github.com/Rob--W/cors-anywhere. So now all are starting to work.
Many thanks!!!