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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |