Random Quote Machine : how to load json file on Codepen?

Hi everyone :slight_smile:

I’ve worked on the Random Quotes Machine, and it works correctly, here’s the result, from my server :

http://dt-quotes-machine.livehost.fr/

I’ve used a json file for the data, that you can find here : https://github.com/4skinSkywalker/Database-Quotes-JSON/blob/master/quotes.json

The problem is that when I try to import the code on codepen, in order to submit my work for the challenge, it doesn’t work. It seems like codepen cannot load the json file from my server.

Here’s the script :

$(document).ready(function(){
                $.getJSON('json/quotes.json', function(json){

                    var indice = Math.floor((Math.random() * 5421) + 1);

                    function newQuote(i){
                        var tweetUrl;

                        $('#quote-text').html(json[i].quoteText);

                        if(json[i].quoteAuthor == ''){

                            $('#quote-author').html('unknown');

                            tweetUrl = 'https://twitter.com/intent/tweet?text=' + json[i].quoteText + ' ' + 'unknown' + '&hashtags=quotes';

                        }else{

                            $('#quote-author').html(json[i].quoteAuthor);
                            tweetUrl = 'https://twitter.com/intent/tweet?text=' + json[i].quoteText + ' ' + json[i].quoteAuthor + '&hashtags=quotes';

                        }
                        $('#tweet-btn').attr('href',tweetUrl);
                    }
                    newQuote(indice);
                    $('#new-quote-btn').click(function(){
                        indice = Math.floor((Math.random() * 5421) + 1);
                        newQuote(indice);
                    });
                });
            });

For codepen, I just tried to adapt the script, by modifying the address of the json file by using :

$.getJSON('http://dt-quotes-machine.livehost.fr/json/quotes.json', function(json){

Full code available here : https://codepen.io/dtettarasar/pen/OxZrLv?editors=0011

But that doesn’t work :confused: and I didn’t found any explanation, maybe a security issue that avoid the json file loading, I don’t know.

Did anyone of you had encountered a similar issue ? if yes how did you resolve the problem ?

Or is there any other way to load a json file on codepen ?

Thanks in advance for your help ^^ !

You didn’t import jQuery. Also, most browsers will block http requests if the page itself is loaded over https. You can work around this by using https://raw.githubusercontent.com/4skinSkywalker/Database-Quotes-JSON/master/quotes.json instead of a file on your own server.

1 Like

Hi,

See my code:

You can do like that.

Regards

Yep you’re right ! I’ve followed your advices and it works now ^^

Thanks a lot !