Search code examples
jqueryjsonjson-api

Getting JSON with the jQuery getJSON Method


I am trying to use JSON from an api to generate random quotes. On the click of the button , the json should populate in place of "The message will go here". But I am finding stuck. The code is below and link for project:

https://codepen.io/monsieurshiva/pen/awBbEE

<html>
<head>

  <script>
  $(document).ready(function() {

    $("#getMessage").on("click", function(){

      $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
  $(".message").html(JSON.stringify(json));
});

    });

  });
</script>
</head>
<body>
      <div class = "col-xs-12 well message">
      The message will go here
    </div>
        <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
</body>
</html>

Solution

  • Please Try This Its Working For Me without Cross Domain Error. I have changed it to a function and use ajax to take data. Also Use https api URL to avoid insecure script error.

        <html>
        <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
          <script>
          $(document).ready(function() {
        
        
        
        $( function() {   
          $('#getMessage').on( 'click', function(){ 
            load();
             } );  
        });
                       
                        var linkUrl = "https://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en";
                        var load = function() {
                                $.ajax(
                                {
                                        dataType : "jsonp",
                                        jsonp : "jsonp",
                                        url : linkUrl,
                                        success : function(response){
                                                $(".message").html(response.quoteText);
                                        }
                                });
                        };
        
          });
        </script>
        </head>
        <body>
              <div class = "col-xs-12 well message">
              The message will go here
            </div>
                <button id = "getMessage" class = "btn btn-primary">
                Get Message
              </button>
        </body>
        </html>