Rectangle 27 1

javascript jQuery AJAX submit form?


$("#idForm").submit(...)
$("#submitButtonId").click(...)
// this is the id of the form
$("#idForm").submit(function(e) {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

Also in this context you can do data: $(this).serialize(), instead of data: $("#idForm").serialize(), which enables us to specify which form in just one location.

Instead of return false you should be using e.preventDefault() to allow further event propagation after your click handler is complete. Using e.preventDefault() will only stop the default action of the Submit button (e.g. to submit the form) but will allow any other events bound to that form to execute. See: fuelyourcoding.com/jquery-events-stop-misusing-return-false

Instead of specifying the url to your script here you could just use the forms ACTION attribute which is normally specified: var url = $(this).attr('action');

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


$("#idForm").submit(...)
$("#submitButtonId").click(...)
// this is the id of the form
$("#idForm").submit(function(e) {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

Also in this context you can do data: $(this).serialize(), instead of data: $("#idForm").serialize(), which enables us to specify which form in just one location.

Instead of return false you should be using e.preventDefault() to allow further event propagation after your click handler is complete. Using e.preventDefault() will only stop the default action of the Submit button (e.g. to submit the form) but will allow any other events bound to that form to execute. See: fuelyourcoding.com/jquery-events-stop-misusing-return-false

Instead of specifying the url to your script here you could just use the forms ACTION attribute which is normally specified: var url = $(this).attr('action');

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


$("#idForm").unbind().submit( function(e) {
  ....

Don't forget to unbind submit event, before the form submited again, User can call sumbit function more than one time, maybe he forgot something, or was a validation error.

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


<form id="contactForm1" action="/your_url" method="post">
    <!-- Form input fields here (do not forget your name attributes). -->
</form>

<script type="text/javascript">
    var frm = $('#contactForm1');

    frm.submit(function (e) {

        e.preventDefault();

        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    });
</script>

Another similar solution using attributes defined on the form element:

Any suggestions on how to do this if the name attribute includes a "."? (Server-side requirement, not my idea).

If you don't set method or action, they default to get and the current URL respectively. Could do with adding this assumption to the code.

Using this with a Symfony2 form, and it's a brilliant elegant solution.

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


<form id="contactForm1" action="/your_url" method="post">
    <!-- Form input fields here (do not forget your name attributes). -->
</form>

<script type="text/javascript">
    var frm = $('#contactForm1');

    frm.submit(function (e) {

        e.preventDefault();

        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    });
</script>

@superluminary Your are right, I have fixed the answer.

Also, return false should be event.preventDefault();

Another similar solution using attributes defined on the form element:

Any suggestions on how to do this if the name attribute includes a "."? (Server-side requirement, not my idea).

If you don't set method or action, they default to get and the current URL respectively. Could do with adding this assumption to the code.

Nice, this solves the problem and is better than the accepted answer :)

This is a better solution, since it pulls the url and method from the form itself. I'd prefer it if it wasn't presented as inline JavaScript though.

Using this with a Symfony2 form, and it's a brilliant elegant solution.

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theForm').serialize())
.ajaxForm()
.ajaxSubmit()

It's serialized into a query string, just like the data you are putting into the array manually in the GET call there would be. This is what you want, I'm pretty sure.

Yes you can, the name isn't important what it will do is send pairs of every form-key and every form-variable.

You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.

ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.

interesting idea, however, i do not control the server side I am calling, therefore I cannot send it serialized data

oooh I see, I then add this string to the end of the URL in the get call. I was thinking PHP serialize. Sorry. Thanks!

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


$("#idForm").unbind().submit( function(e) {
  ....

Don't forget to unbind submit event, before the form submited again, User can call sumbit function more than one time, maybe he forgot something, or was a validation error.

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theForm').serialize())
.ajaxForm()
.ajaxSubmit()

It's serialized into a query string, just like the data you are putting into the array manually in the GET call there would be. This is what you want, I'm pretty sure.

Yes you can, the name isn't important what it will do is send pairs of every form-key and every form-variable.

You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.

ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.

interesting idea, however, i do not control the server side I am calling, therefore I cannot send it serialized data

oooh I see, I then add this string to the end of the URL in the get call. I was thinking PHP serialize. Sorry. Thanks!

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
    (function($){
        $("body").on("submit", ".my-form", function(e){
            e.preventDefault();
            var form = $(e.target);
            $.post( form.attr("action"), form.serialize(), function(res){
                console.log(res);
            });
        });
    )(jQuery);
</script>
HTTP_X_REQUESTED_WITH
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //is ajax
}
jQuery(document).click(function(e){
    var self = jQuery(e.target);
    if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
        e.preventDefault();
        var form = self.closest('form'), formdata = form.serialize();
        //add the clicked button to the form data
        if(self.attr('name')){
            formdata += (formdata!=='')? '&':'';
            formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
        }
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: formdata, 
            success: function(data) {
                console.log(data);
            }
        });
    }
});
jQuery(document).submit(function(e){
    var form = jQuery(e.target);
    if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
        e.preventDefault();
        jQuery.ajax({
            type: "POST",
            url: form.attr("action"), 
            data: form.serialize(), // serializes the form's elements.
            success: function(data) {
                console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
            }
        });
    }
});
  • It will post to the same location as the normal form, specified in the form's "action" attribute
  • You can remove and re-add the form and it will still work
  • You can run this before the document is ready

@YamiMedina that's not a simple solution, you need to send the entire request in a different format (multipart format) with the file data

Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.

How would this work if you DID want to send a file with this form?

I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.

PHP

To support buttons you can capture the actual button click instead of the submit.

Note
Rectangle 27 1

javascript jQuery AJAX submit form?


$(function() {
  $('form.my_form').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: form.serialize()
    }).done(function(data) {
      // Optionally alert the user of success here...
    }).fail(function(data) {
      // Optionally alert the user of an error here...
    });
  });
});
$(function() {
  $('form.my_form').trigger('submit');
});
$(function() {
  $('form[data-autosubmit]').autosubmit();
});
(function($) {
  $.fn.autosubmit = function() {
    this.submit(function(event) {
      event.preventDefault();
      var form = $(this);
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize()
      }).done(function(data) {
        // Optionally alert the user of success here...
      }).fail(function(data) {
        // Optionally alert the user of an error here...
      });
    });
    return this;
  }
})(jQuery)
<form action="/blah" method="post" data-autosubmit>
  <!-- Form goes here -->
</form>

1. There are several ways to submit a form

  • by triggering a submit event in JavaScript
  • possibly more depending on the device or future device.

@mmatt - If JavaScript is disabled, the form is still just a form. The user clicks submit and a regular browser based form submission occurs. We call this progressive enhancement. It's not such a big deal nowadays since modern screen readers support JavaScript.

@mmatt - The promise callbacks will optionally receive a parameter which contains the data.

Add a data-autosubmit attribute to your form tag and you can then do this:

Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:

Hi @Crusader - certainly, instead of having this plugin return this, you could have it return the ajax event, then you could chain right onto it. Alternately you could have the plugin receive a success callback.

I don't see how does this " .. leave it submittable if JavaScript fails" happen here?

The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.

There are a few things you need to bear in mind.

Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.

We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.

We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.

We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.

You can manually trigger a form submission whenever you like via JavaScript using something like:

how can I add the callbacks to 'done' and 'fail' functions? something like $('form[data-autosubmit]').autosubmit().done(function({ ... }); This is possible?

Note