javascript2016 javascript2016 - 3 months ago 14
Javascript Question

Ajax request url and display response in a div is not working?

I am trying to make a ajax request to a website and display only part of it. My code doesn't work and I can't see the reason. Also, how can I parse the object and display only parts of it (just one property)? Thanks a lot!

JS:

$(document).ready(function(){
$('#buttonClick').on('click', 'button',function(){
$.ajax('http://ShakeItSpeare.com/api/sentence', {
success: function(response){
console.log(response)
//console.log of response works
$('.screen').html(response).fadeIn();
}
})
});
});


HTML

<body>
<div id="buttonClick">
<button>click Me</button>
<ul class="screen"></ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<script type="text/javascript" src="shakes.js"></script>
</body>

Answer

Adding the JSON property name you're trying to insert into the HTML should only insert that value. For example, in your code below, I added the "sentence" property in "response.sentence". Also changed .html() to .text().

  $(document).ready(function(){
   $('#buttonClick').on('click', 'button',function(){
    $.ajax('http://ShakeItSpeare.com/api/sentence', {
     success: function(response){
      console.log(response)
   //console.log of response works 
        $('.screen').text(response.sentence).fadeIn();
      }
    })
  });
});

Working code pen: Working Codepen