call ajax while submit form code example

Example 1: ajax submit form data

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

Example 2: ajax submit form data

<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>

Example 3: Sending an Ajax request before form submit

$('form').submit(function(e) { 

     // this code prevents form from actually being submitted
     e.preventDefault();
     e.returnValue = false;

     // some validation code here: if valid, add podkres1 class

     if ($('input.podkres1').length > 0) { 
        // do nothing
     } else {

        var $form = $(this);

        // this is the important part. you want to submit
        // the form but only after the ajax call is completed
         $.ajax({ 
             type: 'post',
             url: someUrl, 
             context: $form, // context will be "this" in your handlers
             success: function() { // your success handler
             },
             error: function() { // your error handler
             },
             complete: function() { 
                // make sure that you are no longer handling the submit event; clear handler
                this.off('submit');
                // actually submit the form
                this.submit();
             }
         });
     }
});

Tags:

Php Example