Hi,
So, I have this code to access an API made to generate random quotes.
$(document).ready(function(){
$('#triggr').on('click', function(e) {
$.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(data) {
console.log(data);
});
});
});
The problem is that it’s showing a CORS error.
This is the error I’m getting.
XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Here is my project link https://buoyantair.github.io/quote-gen/
Hi @udayk8139
The only consistent way I’ve found of getting around cors errors is to use jsonp. If you amend the call to the following, it should work:
$.get("http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(data) {
console.log(data);
}, 'jsonp');
GitHub pages are served over https so any xhr
requests must also use a secure protocol. Otherwise, a browser will block it.
more about mixed content
Hey, I’ve modified my code and this is how it looks right now
function getq(storage){
}
$(document).ready(function(){
var obj;
$('#triggr').on('click', function(e) {
$.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(data) {
obj = data;
$('#quote-text').html(obj.quote);
$('#quote-author').html("By " +obj.author);
$('#quote-source').html("Source: " +obj.permalink);
}, 'jsonp');
$(".content").animate({
opacity: 0,
background: "#FF4081"
}, 100);
$(".quote-content").animate({
background: "#FF4081"
}, 100);
getq(obj)
$(".content").animate({
opacity: 1,
}, 800);
debounce = false
});
$("#tweet-button").on('click', function(){
var tweetUrl = 'https://twitter.com/intent/tweet?text=' + ' "' + encodeURIComponent(obj.quote) + '" ' + " By " + encodeURIComponent(obj.author);
window.open(tweetUrl);
});
});
It still errors, you can check the console output here
https://buoyantair.github.io/quote-gen/
You need to remove the JSON from the get request like so: $.get()
, however, as per what @marzelin said, I’m not sure that will work because github is using https, whereas that endpoint is using http.