Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery AJAX form submit with Twitter Bootstrap modal
jQuery(function($) {
$('form[data-async]').live('submit', function(event) {
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
$target.html(data);
}
});
event.preventDefault();
});
});
<!-- Bootstrap trigger to open modal -->
<a data-toggle="modal" href="#rating-modal">Write a Review</a>
<div class="hide fade modal" id="rating-modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2>Your Review</h2>
</div>
<div class="modal-body">
<!-- The async form to send and replace the modals content with its response -->
<form class="form-horizontal well" data-async data-target="#rating-modal" action="/some-endpoint" method="POST">
<fieldset>
<!-- form content -->
</fieldset>
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Cancel</a>
</div>
</div>
@appastair

This comment has been minimized.

Copy link

commented Jan 9, 2013

This is really modular and elegant! I can't see how I won't continue to use a similar approach in future. Thanks!

@samdoidge

This comment has been minimized.

Copy link

commented Jan 19, 2013

Very nice, thanks.

@vuk-nikolic

This comment has been minimized.

Copy link

commented Jan 28, 2013

Just change .live to .on because it's removed in jquery 1.9.
Anyway, awesome code, thanks :)

@jwebcat

This comment has been minimized.

Copy link

commented Jan 29, 2013

@ vuk-nikolic Agree completely in the docs it says that you should use .on instead of .live for various performance reasons.

@aaesis

This comment has been minimized.

Copy link

commented Jan 31, 2013

I tried your code and i have alittle issues what is the problem why i cant get into post

php code: echo $_POST['fullname'];

html inside the form:

it wont echoed out. why?

@Cognis

This comment has been minimized.

Copy link

commented Feb 20, 2013

Amazing. I've been looking for something just like this. It works great. Thank you very much for this code :D

@Dj1bs

This comment has been minimized.

Copy link

commented Mar 1, 2013

I tried your code, it's seems to be easy but the validation page opens in a new page, not into the modal like the form, have you a demo please ??

@djiesamsoe

This comment has been minimized.

Copy link

commented Apr 30, 2013

awesome code for me, thanks mate

@feryardiant

This comment has been minimized.

Copy link

commented Jun 5, 2013

You safe my days @havvg. thanks a lot!

@AzeemMichael

This comment has been minimized.

Copy link

commented Jun 11, 2013

thanks, this helped a lot -- I added my submit button in the "modal-footer" like this.

<form id="ratting-form"

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    <button form="ratting-form" class="btn btn-primary" type="submit">Save changes</button>
</div>
@tlongren

This comment has been minimized.

Copy link

commented Jun 26, 2013

Hey this looks pretty nice. I may replace my go-to code for this type of thing with this gist.

@ssh222

This comment has been minimized.

Copy link

commented Jul 2, 2013

Very good! However I have one problem.
When I open form and then submit it and echo some "success message", and then open it again from the link, I get the "success message". How to avoid this? Maybe I need somehow to reload the DOM after the form is successfully submitted?

@jessicaferrari

This comment has been minimized.

Copy link

commented Jul 5, 2013

Heyyyyyyyyyyyyyyy don't work =D
=.='

@shivsharma

This comment has been minimized.

Copy link

commented Aug 13, 2013

not working

@NicoJuicy

This comment has been minimized.

Copy link

commented Oct 29, 2013

nice and clean :)

@leeglick

This comment has been minimized.

Copy link

commented Nov 18, 2013

this works great with Bootstrap 2 but is broken for me with Bootstrap 3 -- anyone have tips for making it Bootstrap 3 compatible?

@wmandai

This comment has been minimized.

Copy link

commented Nov 28, 2013

Really helpful :) Thanks a ton

@Batistleman

This comment has been minimized.

Copy link

commented Dec 4, 2013

Nice Gist, to get this to work with boostrap 3 and latest jquery try:

jQuery(function($) {
    $('form[data-async]').on('submit', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));

        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                $target.modal('hide');
            }
        });

        event.preventDefault();
    });
});
@touch2hussain

This comment has been minimized.

Copy link

commented Dec 20, 2013

even i face this problem... plz help...When I open form and then submit it and echo some "success message", and then open it again from the link, I get the "success message". How to avoid this?

@vongosling

This comment has been minimized.

Copy link

commented Jan 13, 2014

Good!

@xomero

This comment has been minimized.

Copy link

commented Jan 30, 2014

Hi, I'm trying to load a custom form in the modal, like send some params via Ajax, load the form in the modal, and then do the submit (ajax submit like yout code)

Any Idea?

Thank you

@BurnedToast

This comment has been minimized.

Copy link

commented Feb 11, 2014

There are 2 problems with this code

  1. it wont submit the submit-button value
  2. if you replace live with on, the JS wont trigger if the modal is a remote-Modal

I fixed this issues with the following code:

jQuery(function($) {
    $(document).on('submit', 'form[data-async]', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));
        var submitButton = $("input[type='submit'][clicked=true], button[type='submit'][clicked=true]", $form);

        var formData = $form.serializeArray();
        if (submitButton.size() === 1) {
            formData.push({ name: $(submitButton[0]).attr("name"), value: "1" });
        }
        else if(submitButton.size() !== 0) {
            console.log("Multiple submit-buttons pressed. This should not happen!");
        }

        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: formData,

            success: function(data, status) {
                $target.html(data);
            }
        });

        event.preventDefault();
    });

    $(document).on("click", 'input[type="submit"], button[type="submit"]', function() {
        $('form[data-async] input[type=submit], form[data-async] button[type=submit]', $(this).parents("form")).removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
});

Please let me know if someone knows a better way to determinate the pressed submit button!

@riterrani

This comment has been minimized.

Copy link

commented Mar 4, 2014

<form data-async data-target="event|close|#alert-settings" action="/alerts/settings/save" method="POST">
$('.modal').on('submit','form[data-async]', function(event) {
        var $form = $(this);
        var target = $form.attr('data-target');

        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                $.each(target.split("|"),function(i,val){
                    if(val == "close"){
                        $form.closest(".modal").modal("hide");
                    }else if(val == "event"){
                        $form.trigger("ajax-submit");
                    }else{
                        $(val).html(data);
                    }
                });
            }
        });

        event.preventDefault();
    });
@webIMT

This comment has been minimized.

Copy link

commented Mar 5, 2014

Hi,

the code from @BurnedToast is OK but only at the first click on submit button cause, at the second click, two posts are sent, at the third, three, etc...

Is there any solution ?

My code :

   $('.modal').on('submit', 'form[data-async]', function(e) {
        var $form = $(this);
        var enctype = $form.attr('id')

        if(enctype == 'multipart') {
            var formData = new FormData(this);

            $.ajax({
                type: $form.attr('method'),
                url: $form.attr('action'),
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,

                success: function(data, status) {
                    $('#remoteModal .modal-content').html(data);
                }
            });
        }
        else {
            var submitButton = $("input[type='submit'][clicked=true], button[type='submit'][clicked=true]", $form);
            var formData = $form.serializeArray();

            if(submitButton.size() === 1) {
                formData.push({ name: $(submitButton[0]).attr("name"), value: "1" });
            }
            else if(submitButton.size() !== 0) {
                console.log("Weird, multiple submit-buttons pressed!");
            }

            $.ajax({
                type: $form.attr('method'),
                url: $form.attr('action'),
                data: formData,
                cache: false,

                success: function(data, status) {
                    $('#remoteModal .modal-content').html(data);
                }
            });
        }

        e.preventDefault();
    });

    $('.modal').on("click", 'input[type="submit"], button[type="submit"]', function() {
        $('form[data-async] input[type=submit], form[data-async] button[type=submit]', $(this).parents("form")).removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
@brojask

This comment has been minimized.

Copy link

commented Mar 21, 2014

Thank you so much!

@ProNotion

This comment has been minimized.

Copy link

commented Jul 2, 2014

I am trying to get this working with Bootstrap 3 and a form which is using jQuery Unobtrusive validation (in case that makes a difference). For some reason the form is performing a full page submit. I've added alerts to the script in multiple places but none are ever triggered.

Here is my code if anyone can see anything wrong?

jQuery(function ($) {
    $('form[data-async]').on('submit', function (event) {

        alert("async form");

        var $form = $(this);
        var $target = $($form.attr('data-target'));

        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),
            success: function (data, status) {
                alert(status);
                $target.modal('hide');
            },
            error: function (result) {
                alert(result);
            }
        });
        event.preventDefault();
    });
});

I am using jquery-1.9.0.js. I notice just before the page submits that an error gets generated in the console as follows:

"Unexpected token u" and seems to break on the following line in the jQuery source:

return window.JSON.parse( data );

The value of data at this point is true but not sure where the value has come from.

@nobutsta

This comment has been minimized.

Copy link

commented Feb 2, 2016

@BurnedToast is working but @riterrani can close the modal after a submit is clicked!

@codeblood10

This comment has been minimized.

Copy link

commented Jul 25, 2016

simply awesome man!!!

@hzb

This comment has been minimized.

Copy link

commented Jul 30, 2016

@BurnedToast I try your code, but there is an issue here

$(document).on('submit', 'form[data-async]', function(event) {

if I change it to

$(document).on('submit', function(event) {

Works!

@frozenade

This comment has been minimized.

Copy link

commented Sep 24, 2016

Hi, how to add loading indicator while saving?

@garciacrew

This comment has been minimized.

Copy link

commented Jan 13, 2018

@frozenade Put a div with id name of your choice and first line of the function add. In my example below I named the div id="processing"

$('#processing').html("<b>Saving...</b>");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.