1

I have this html code:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div id="result" style="color:red"></div>
</div>
</body>
<script>

  $(document).ready(function(){

  $.ajax({
        url: "https://api.github.com/users/Microsoft",
        type: 'GET',
        dataType: 'json',
        success: function(res) {
           $('#result').html(res)
        }
    });

})

</script>

Whenever I try to see the result on my browser it just shows an empty blank page.

I just need to return the API result and show it on html.

Any ideas?

4
  • 1
    Have you tried using network monitor available in devtools of your browser to inspect the server's response? Maybe use $('#result').text(JSON.stringify(res)) instead of your line. To analyse the issue, insert console.log( res ); right before that line injecting the result into HTML element just to make sure this callback is ever invoked. And see the console for probably showing warning regarding CORS issue. Commented Dec 16, 2018 at 18:45
  • Thank You! That was it, also, excuse me, just a question, do you know how can I format that response? I mean, just an idea, can I put every json item into a different div? Commented Dec 16, 2018 at 18:47
  • 1
    Formatting: don't use a <div>, but a <pre> might help with that, though it still might require to pretty-print the JSON as a string: $('#result').text(JSON.stringify(res, null, '\t'));. Commented Dec 16, 2018 at 18:48
  • Thank You very much Commented Dec 16, 2018 at 18:51

1 Answer 1

3

The AJAX callback makes res an object. When you using .html() the argument must be a string. If you want to see the object represented on the page, use JSON.stringify():

$.ajax({
    url: "https://api.github.com/users/Microsoft",
    type: 'GET',
    dataType: 'json',
    success: function(res) {
       $('#result').html(JSON.stringify(res))
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'd stick with .text() instead of .html() just to make sure any contained < isn't parsed as HTML ... it's performing better, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.