Skip to content

onSuccess, calling external function to submit form data via Ajax

Steve Wasiura edited this page Aug 30, 2014 · 1 revision

Here is one example of using the onSuccess property to call an external function to submit the form via jQuery's Ajax method.

When assigning the value of the property onSuccess, if you define it as a function, the validation class will invoke that function.

Inside that function, you can call your external function.

You can pass the jQuery form object to the onSuccess function, and then pass it to the external function again as an argument.

In your external function, return false to prevent the browser from redirecting to the URL listed in the form's action property.

// call jQuery form validation function
        $.validate(
                {   // don't validate when element loses focus
                    validateOnBlur : false,
                    // validation successful, call function to send the form post data to server
                    onSuccess : function(form) { return $.sendFormDataViaAJAX(form); }
                }
        );

// formSubmit via ajax *********************************************************
// post using the comment form & get back response from server & display on page.
$.sendFormDataViaAJAX = function(form) 
{   console.log('form data sent via ajax');
    

    
    var thisForm = form;
    console.log(thisForm);

            // reveal graphic to show in progress
            $(thisForm).find("#form_submit_progress").show();
            
            // disable submit button
            $('input[type=submit]').attr('disabled', 'disabled');
            
            /* setup post function vars */
            var targetUrl =     $(thisForm).attr('action');
            var formData =      $(thisForm).serialize();
            console.log(formData);
                
            /* send the data using post and put the results in a div with id="result" */
            /* post(url, postcontent, callback, datatype returned) */
            var request = $.ajax(
            {   url: targetUrl,
                type: "POST",
                data: formData,
                dataType: "json",
                success: formPostCompleted,
                statusCode: 
                {409:validationServerFailed,
                 500:serverError
                }
            }
            );// end ajax function


            // formPostCompleted ***************
            // internal function called from jQuery ajax method
            function formPostCompleted(data, status) 
            {    // write server response to console for troubleshooting
                    console.log(data);
                    console.log(status);
                    
                 // hide graphic that shows form processing in progress
                $('#form_submit_progress').hide();
                    
                    // check if success
                    if (data.success)
                    {   
                        // show success message
                        $('.alert-message.success').fadeIn(1000); 
                        
                        // scroll up to the success message div
                        $('html,body').animate({scrollTop: $(".alert-message.success").offset().top}, 'fast');
                       
                    } // end if success
            }// end formPostCompleted function *****************   

                
            // validationServerFailed ***************
            // internal function called from jQuery ajax method when http status code=409
            function validationServerFailed(serverData)  
            {    // write server response to console for troubleshooting
                 console.log(serverData);
                    
                 // hide graphic that shows form processing in progress
                $('#form_submit_progress').hide();
                
                // parse the responseText json formatted string into a js object
                var data = jQuery.parseJSON(serverData.responseText);
                
                 // test if validation not correct
                 if (!data.validation_passed)
                 {   // for each errMsg, red outline form field, show msg
                     $.each(data.validation_messages, 
                        function(key, value) 
                        {   // change form field border to red
                         //   $('#'+key).css('border-color', 'red');
                            // add class to form field
                            $('#'+key).addClass('error');
                            // get validation err msg from form field attr
                            var errMsg = $('#'+key).attr('data-validation-error-msg');
                            // create span, fill with errMsg, insert after input element
                            $('<span class="error">'+errMsg+'</span>').insertAfter('#'+key);
                        }
                      );
                     
                 } // end if validation not correct
 
                 // re-enable the submit button
                 $('input[type=submit]').attr('disabled',false);
                 $('input[type=submit]').removeAttr('disabled');
                
            }// end validationServerFailed function *****************
            
            
            
            // serverError **********************
            // internal function called from jQuery ajax method if server responds with 500 error
            function serverError(object, data, status) 
            {   
                // show server error message
                $('#server_error_message').html('Sorry, an error has occurred. The website administrator has been notified.');
                $('#server_error_message').css({'background-color':'yellow'});
                $('#server_error_message').show();    

                // hide graphic that shows form processing in progress
                $(thisForm).find("#form_submit_progress").hide();
                
                // re-enable the submit button
                $('input[type=submit]').attr('disabled',false);
                $('input[type=submit]').removeAttr('disabled');
            }// end serverError ********************************

    return false; // prevent browser from submitting the form to the action property URL    
}; // end sendFormDataViaAJAX *****************************************************
Clone this wiki locally