Agyan
adda
Run
Reset
Copy
jQuery Tutorial › jQuery get() and post() › POST a form with jQuery
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <form id="comment"> <input name="title" placeholder="Title" required><br><br> <textarea name="body" placeholder="Comment" rows="3" required></textarea><br> <button>Post comment</button> </form> <p id="msg"></p> <script> $(function () { $('#comment').on('submit', function (e) { e.preventDefault(); const $btn = $(this).find('button').prop('disabled', true).text('Posting...'); $.post('https://jsonplaceholder.typicode.com/posts', $(this).serialize()) .done(function (res) { $('#msg').css('color', 'green').text('Saved! Server gave it id ' + res.id + '.'); $('#comment')[0].reset(); }) .fail(function (xhr) { $('#msg').css('color', 'crimson').text('Error ' + xhr.status + '. Please try again.'); }) .always(function () { $btn.prop('disabled', false).text('Post comment'); }); }); }); </script>
Result