Skip to content Skip to sidebar Skip to footer
Reading Time: 2 minutes

If you have too many forms to submit via ajax you can use the below speedy code to do that. Only you have to call to that function via parameters. Great script with custom validations.

You must include jQuery library file and jquery.validation.js file. I have used this my own code for PHP CodeIgniter.

1-My form submit ajax function

$.fn.webExForm = function(options) {
      var defaults = {
            ajaxSubmit: true,
            dataType: "json",
        onModalClose: function() {
            },
            onSuccess: function() {
            },
            onError: function() {
                return true;
            },
            onSubmit: function() {
            },
            onAjaxSuccess: function() {
            },
            beforeAjaxSubmit: function(data, self, options) {
            }
      };
      var settings = $.extend({}, defaults, options);
      this.each(function(e) {
 			 if (settings.ajaxSubmit) {
               validateForm($(this), function(form) {
         	   $.ajax({
                 type: "POST",
                 url: $(form).attr('action'),
                 data: $(form).serialize(),
                 dataType: settings.dataType,
                                success: function(result) {
                                   if (result.success) {
                                    settings.onSuccess(result);
                                   } else {
                                       if (settings.onError(result)) {
                                         if (result.message) {
                       settings.onError(result);
                                         }
                                       }
                                  } // end else
                                 },
                 onError: function() {
                    return false;
                 },
                           });
 	  		});
               } else {
                             validateForm($(this));
                         }
});
    function validateForm(form, customSubmit) {
        $(form).validate({
                submitHandler: function(form) {
                    if (customSubmit) {
                        customSubmit(form);
                    } else {
                        return true;
                    }
                },
                highlight: function(element) {
                    $(element).closest('.form-group').addClass('has-error');
                },
                unhighlight: function(element) {
                    $(element).closest('.form-group').removeClass('has-error');
                },
                errorElement: 'span',
                errorClass: 'help-block',
                ignore: ":hidden:not(.validate-hidden)",
                errorPlacement: function(error, element) {
                    if (element.parent('.input-group').length) {
                        error.insertAfter(element.parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });
        }
    };

 

2-HTML form

<form id="loginForm" method="post" name="loginForm">
<input name="username" type="text" /> 
<input name="password" type="text" /> 
<input type="submit" name="login" value="Login" />
</form>

 

3-Call to function

$("#loginForm").webExForm({ 
    isModal: false, 
    onSubmit: function() { 
        $('#ajax-loader-icon').show(); 
    }, 
    onSuccess: function(result) { 
        $('#ajax-loader-icon').hide(); 
        alert(result.message); 
    }, 
    onError: function(result) { 
        alert(result.message); 
        return false; 
    } 
});

 

4-Server response

// if success 
echo json_encode(array("success" => true, 'message' => 'Successfully saved.' )); 

// if error 
echo json_encode(array("success" => false, 'message' => 'Error occurred.' ));

 

You have the below advantages:
1-Can submit form via ajax using few code
2-Call back function
3-call before submit
4-Call after submit
5-Json encode method
6-Serialized form data
7-No need to call each input fields
8-Can use for large or any scale of form
9-Inbuilt validations
10-Fast and clean code.