Skip to content

Instantly share code, notes, and snippets.

@Mr-Kumar-Abhishek

Mr-Kumar-Abhishek/index.js Secret

Last active Dec 5, 2016
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@TylerMoeller 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

This comment has been minimized.

Copy link
Owner Author

@Mr-Kumar-Abhishek 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