Write jQuery code to submit a form with Ajax

Description: Submit the contact form in the background, and show the message from the server below the form.

Hint:

  • Use e.preventDefault(), .serialize() and $.ajax().

HTML of the page

<form id="contact" action="send" method="post">
  <input type="text" name="name" value="Anita">
  <input type="email" name="email" value="anita@example.com">
  <button type="submit">Send</button>
</form>
<p id="result"></p>

Solution

$('#contact').on('submit', function (e) {
  e.preventDefault();

  $.ajax({
    url: $(this).attr('action'),
    method: $(this).attr('method'),
    data: $(this).serialize(),
    dataType: 'json'
  }).done(function (res) {
    $('#result').text('Server received: ' + res.received);
  }).fail(function () {
    $('#result').text('Sorry, there was an error.');
  });
});

$('#contact').trigger('submit');
HTML after the code runs

<p id="result">Server received: name=Anita&email=anita%40example.com</p>

How it works

  • The data is sent as name=Anita&email=anita%40example.com. Here the test server only repeats it.
  • The page is not reloaded, and the result is shown in the paragraph.

Read jQuery Forms and jQuery Ajax.


Learn more about the similar topics:
Tutorials
jQuery load() Method
jQuery Ajax: ajax(), get(), post() and getJSON()
jQuery Deferred, Promises and $.when()
Exercises & Assignments
Write jQuery code to load JSON data with Ajax and show it in a list
Write jQuery code to submit a form with Ajax
Interview Questions & Answers
How do you make an Ajax call in jQuery?
What is the difference between $.get(), $.post() and $.ajax() in jQuery?
What are Deferred objects and promises in jQuery?
How do you handle Ajax errors in jQuery?