Search code examples
jqueryajaxasp.net-mvcrazorajaxform

How to get event between Ajax.BeginForm and OnSuccess?


I have a form, which I submit using Ajax.BeginForm. I want to do the following:

  1. Submitting the form with all the data (using Ajax.BeginForm)
  2. While we're waiting for the controller, do some work - including truncating my textarea
  3. When the controller is done (using OnSuccess), do some more stuff

However, while 1) and 3) works perfectly, I don't know which way to access #2. I have tried using the JavaScript event submit on the form, but it seems this event happens before, so if I empty my textarea the controller never sees this filled value.

My Razor:

    @using (Ajax.BeginForm("CreateNotification", "Task",null, new AjaxOptions() {HttpMethod = "POST", OnSuccess= "newMessage" },new {id="conv_form"}))
    {
        @Html.HiddenFor(c => c.ConversationId)

        <div class="form-group">
            @Html.TextAreaFor(c => c.New_Message, new {@class = "form-control conversation-box"})
        </div>

        <input type="submit" value="Send message" id="conversation_message_submit" class="btn btn-link pull-right" style="color: black; padding-right: 0px; font-size: 12pt;"/>

    }

I also have my jQuery:

<script>
    $(document).ready(function() {
        /// Here I plan to truncate my textarea + other stuff
        $('#conv_form').submit(function () {
            console.log('conv_form submit');
        });
    });

    function newMessage(data) {
        console.log('newmessage fired');

    }
</script>

So my challenge is that with my submit event, if I manipulate the fields this will change what we send to the controller. I want to access an event which is between what is sent to controller and the OnSuccess.


Solution

  • you can try ajaxStart

     $('#conv_form').submit(function () {
            console.log('conv_form submit');
        });
    }).ajaxStart(function(){
          //DoYourStuff
        })
        .ajaxStop(function(){
            //Stop Your Stuff
        });