0

I have the following Bootstrap contact form:

     <form id="contactForm" class="form-horizontal" data-async data-target="#contact" action="/contact.php" method="POST">
         (...)
         <button class="btn btn-primary pull-right" type="submit">Send</button>
     </form>

And this jQuery code:

$('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.html(data);
        }
    });

    event.preventDefault();
});

I can submit the form and get an AJAX response once but the second time I try to do it it loads contact.php in the navigator. Which I don't get because event.preventDefault() should prevent this. How can I make multiple AJAX calls work?

madth3
  • 7,275
  • 12
  • 50
  • 74
  • 2
    Why not making it just a regular, non-submit button, if you don't want submit to happen? – Vedran Šego May 18 '13 at 19:34
  • @VedranŠego: I made it a submit button so that it triggers the jQuery function. I like that function and I'm going to use it as is somewhere else in the project so I was wondering if there was a way to adapt the current form to allow multiple submissions. –  May 18 '13 at 19:40
  • i dont understand why you need a wrapping form-element´s submit event to handle your action, that could also be called by a click on any element, are you doing this just to make use of .serialize()? – john Smith May 18 '13 at 19:41
  • Yes. That way the same method is used in all AJAX calls of the project. It looks like it's making things harder instead of easier though. –  May 18 '13 at 19:43

1 Answers1

-1

Try the form+ajax without the complexities as given. If it works then its something with the code.

X10nD
  • 21,638
  • 45
  • 111
  • 152
  • 1
    I went with the code found [here](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example) and it seems to be easier. Thanks for the help! –  May 18 '13 at 20:21