Skip to content

Instantly share code, notes, and snippets.

@Mr-Kumar-Abhishek
Last active December 5, 2016 21:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Mr-Kumar-Abhishek/a19c9c57c76143ae536396155ebae390 to your computer and use it in GitHub Desktop.
Random quote machine http to https
$(document).ready(function() {
$.getJSON("https://crossorigin.me/http://quotes.stormconsultancy.co.uk/random.json",function(data) {
$("#quote").text(data.quote);
$("#author").html(data.author);
$("#tweet_this").attr('href', 'http://www.twitter.com/intent/tweet?text=' + data.quote + ' -- ' + data.author);
});
});
$("#get_quote").click(function(){
$.getJSON("https://crossorigin.me/http://quotes.stormconsultancy.co.uk/random.json",function(data) {
$("#quote").text(data.quote);
$("#author").html(data.author);
$("#tweet_this").attr('href', 'http://www.twitter.com/intent/tweet?text=' + data.quote + ' -- ' + data.author);
});
});
@TylerMoeller
Copy link

TylerMoeller commented Dec 4, 2016

To avoid code duplication and using the proxy when it isn't needed, you can do:

$(document).ready(function () {
  getQuote();
  $('#get_quote').click(getQuote);
});

function getQuote() {
  var url = 'http://quotes.stormconsultancy.co.uk/random.json';
  if (window.location.protocol !== 'http:') url = 'https://crossorigin.me/' + url;
  $.getJSON(url).done(function (data) {
    $('#quote').text(data.quote);
    $('#author').html(data.author);
    $('#tweet_this').attr('href', 'http://www.twitter.com/intent/tweet?text=' + data.quote + ' -- ' + data.author);
  });
}

Edit: Also, you'll want to encode your Twitter text, or tweets will get cut off at punctuation.

@Mr-Kumar-Abhishek
Copy link
Author

Mr-Kumar-Abhishek commented Dec 5, 2016

@TylerMoeller I tried a similar solution for code duplication, however doing it this way it doesn't loads the quote automatically when someone opens/refreshes the page. Also, https://crossorigin.me/ doesn't work in both of the versions codes in my system. If it works in yours then , I don't know what is going on.

My system has the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://crossorigin.me/http://quotes.stormconsultancy.co.uk/random.json. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I will update here if anything works.

Edit: your solution works for avoiding code duplication

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment