skip to Main Content

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.

I have the below Code.

@using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { @class = "form-horizontal", id = "formID" }))
{

}

$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
    FunctionToBeCalled(); //JS function
}
}

But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().

So I made the below changes by referring this link. But now the APIMethod is getting called twice.

$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
    $.ajax({
        url: $('#formID').attr('action'),
        type: 'POST',
        data: $('#formID').serialize(),
        success: function () {
            console.log('form submitted.');
            FunctionToBeCalled(); //JS function
        }
    });

}
}
function FunctionToBeCalled(){alert('hello');}

So I am not able to solve the issue.

5

Answers


  1. If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.

    View:

    $('form').submit(function (event) {
        event.preventDefault();
    
        var formdata = $('#demoForm').serialize();
        //If you are uploading files, then you need to use "FormData" instead of "serialize()" method. 
        //var formdata = new FormData($('#demoForm').get(0)); 
     
        $.ajax({
            type: "POST",
            url: "/DemoController/Save",
            cache: false,
            dataType: "json",
            data: formdata,
     
            /* If you are uploading files, then processData and contentType must be set to 
            false in order for FormData to work (otherwise comment out both of them) */
            processData: false, //For posting uploaded files
            contentType: false, //For posting uploaded files
            //
     
            //Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
            beforeSend: function () {
                //e.g. show "Loading" indicator
            },
            error: function (response) {
                $("#error_message").html(data);
            }, 
            success: function (data, textStatus, XMLHttpRequest) {
                $('#result').html(data); //e.g. display message in a div
            }, 
            complete: function () {
                //e.g. hide "Loading" indicator
            },
        });
    });
    

    Controller:

    public JsonResult Save(DemoViewModel model)
    {
        //...code omitted for brevity
        return Json(new { success = true, data = model, message = "Data saved successfully." 
    }
    

    Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.

    function save(event) { 
        //Validate the form before sending the request to the Controller
        if (!$("#formID").valid()) {
            return false;
        }
        ...
    }
    
    Login or Signup to reply.
  2. Update your function as follows.

    $('#formID').submit(function (e) {
        e.preventDefault();
        try{    
          $.validator.unobtrusive.parse("form");          
          if ($(this).valid()) {              
              $.ajax({
                  url: $('#formID').attr('action'),
                  type: 'POST',
                  data: $('#formID').serialize(),
                  success: function () {
                      console.log('form submitted.');
                      FunctionToBeCalled(); //JS function                      
                  }
              });    
          }
        }
        catch(e){
          console.log(e);
        }                
    
    });
    

    Check the browser console for fetching error. The above code will prevent of submitting the form.

    I think line $.validator.unobtrusive.parse(“form”) were throwing error.
    For that use you need to add the following jQuery libraries.

    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script> 
    
    Login or Signup to reply.
  3. The major thing here is that I didn’t use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked

    You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.

    (function() {
        $(function() {
            var _$pageSection = $('#ProccessProductId');
            var _$formname = _$pageSection.find('form[name=productForm]');
    
            _$formname.find('.buy-product').on('click', function(e) {
    
              e.preventDefault();
    
              if (!_$formname.valid()) {
                return;
              }
              var formData = _$formname.serializeFormToObject();
    
              //set busy animation
    
              $.ajax({
                url: 'https://..../', //_$formname.attr('action')
                type: 'POST',
                data: formData,
                success: function(content) {
                  AnotherProcess(content.Id)
                },
                error: function(e) {
                  //notify user of error 
                }
              }).always(function() {
                // clear busy animation
              });
            });
    
    
            function AnotherProcess(id) {
    
              //Perform your operation
            }
          }
        }
    <div class="row" id="ProccessProductId">
    
      @using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { @class = "form-horizontal", name="productForm" id = "formID" })) {
      <li class="buy-product"><a href="#">Save & Proceed</a></li>
      }
    
    </div>
    Login or Signup to reply.
  4. I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:

    Here is the revised version of your code :

    <form method="post" id="formID">
        <!-- Your form fields here -->
        <button id="submit">Submit</button>
    </form>
    

    Submit your form on button click like:

    $('#submit').on('click', function (evt) {
            evt.preventDefault();
            $.ajax({
                url: "/Configuration/APIMethod",
                type: 'POST',
                dataType : 'json',
                data: $('#formID').serialize(),
                success: function () {
                   console.log('form submitted.');
                   FunctionToBeCalled(); //JS function
               }
           });
    });
    
    function FunctionToBeCalled(){alert('hello');}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search