jQuery

How to Submit a Form Using jQuery Ajax ($.ajax)

Last updated: 09.10.2025
Views: 446

Submitting a form using jQuery’s $.ajax method is a powerful way to send data to the server without reloading the page. This approach improves user experience and allows for more dynamic interactions. You can handle form submissions in multiple ways, either by serializing the entire form or manually collecting input values.

Example 1: Using serialize()

The serialize() function automatically encodes all form fields into a query string format. Here’s how you can use it:

HTML

<form id="myForm">
  <input type="text" name="username" />
  <input type="email" name="email" />
  <button type="submit">Send</button>
</form>

JavaScript

$('#myForm').on('submit', function(ev) {
    ev.preventDefault(); // prevent default form submit
    $.ajax({
      type: 'POST',
      url: '/submit.php',
      data: $(this).serialize(),
    }).done(function(response){
      console.log('Server response:', response);
    }).fail(function(){
      console.log('Submission failed.');
    });
});

In this case, all form inputs are automatically gathered and sent via POST.

Example 2: Manually Collecting Form Data

If you need more control (e.g., custom processing or excluding fields), you can build the data object yourself:

JavaScript

$('#myForm').on('submit', function(ev) {
    ev.preventDefault(); // prevent default form submit

    const formData = {
      username: $('input[name="username"]').val(),
      email: $('input[name="email"]').val()
    };

    $.ajax({
      type: 'POST',
      url: '/submit.php',
      data: formData,
    }).done(function(response){
      console.log('Server response:', response);
    }).fail(function(){
      console.log('Submission failed.');
    });
});

Using this method, you can preprocess data before sending it.

Conclusion

Both techniques are effective and depend on your needs. Use serialize() for simple forms and the manual method when you need more flexibility. jQuery’s $.ajax makes form handling cleaner and more interactive, especially for modern web applications.

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

One response to “How to Submit a Form Using jQuery Ajax ($.ajax)”

  1. zoritoler imol says:

    I have been absent for a while, but now I remember why I used to love this website. Thanks, I?¦ll try and check back more often. How frequently you update your site?

Leave a Reply

Your email address will not be published. Required fields are marked *