Andy Andy - 4 months ago 19
Javascript Question

jQuery API not working with JavaScript

Using a Mashape API for random quotes, but nothing happening on click. Below is the JS and HTML. Is there something wrong with the JS code? When I click the button, nothing happens. The quote is not appearing in the

div
. Thanks!

$('#getQuote').click(function (){
$.ajax({
headers: {
'X-Mashape-Key': 'nrXbQkfuWEmshxvDCunSMptEn0M0p1jHWCijsnX9Ow18j8TXus',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
method:'POST',
dataType: 'json',
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/',
success: function(response) {
var ape = JQuery.parseJSON(response)
var quoteText = ape.quote;
var quoteAuthor = ape.author;
$(".quote").html(quoteText);
$(".author").html(quoteAuthor);}
});
});



<body>
<div class = "quote">quote</div>
<div class = "author">author</div>
<div id="button">
<button id="getQuote">Get Quote</button>
</div>
</body>

Answer

Prevent the default click event, remove the parsing of the data:

$(function(){
    $('#getQuote').click(function (e){
            e.preventDefault();
            $.ajax({
              headers: {
                'X-Mashape-Key': 'nrXbQkfuWEmshxvDCunSMptEn0M0p1jHWCijsnX9Ow18j8TXus',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
              },
              method:'POST',
              dataType: 'json',
              url: 'https://andruxnet-random-famous-quotes.p.mashape.com/',
              success: function(response) {
                var ape = response//remove the parsing
                var quoteText = ape.quote;
                var quoteAuthor = ape.author;
                $(".quote").html(quoteText);
                $(".author").html(quoteAuthor);}
            });
          });
});

https://jsfiddle.net/cyLyn8ba/