Agyan
adda
Run
Reset
Copy
jQuery Tutorial › jQuery AJAX Introduction › Load JSON without reloading
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <button id="load">Load a random post</button> <div id="post" style="margin-top:10px;padding:12px;border:1px solid #ddd;max-width:420px">Click the button.</div> <script> $(function () { $('#load').click(function () { const id = Math.floor(Math.random() * 100) + 1; $('#post').text('Loading...'); $.getJSON('https://jsonplaceholder.typicode.com/posts/' + id) .done(function (data) { $('#post').empty() .append($('<h4>').text('#' + data.id + ' ' + data.title)) .append($('<p>').text(data.body)); }) .fail(function () { $('#post').text('Could not load the post. Check your internet connection.'); }); }); }); </script>
Result