Lars Holdgaard
Lars Holdgaard

Reputation: 9966

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.

Upvotes: 1

Views: 1022

Answers (2)

Ali Soltani
Ali Soltani

Reputation: 9927

You can use ajaxStart for do step 2 like this:

$(document).ajaxStart(function() {
   // do step 2
});

The ajaxStart() method specifies a function to be run when an AJAX request starts. As of jQuery version 1.9, this method should only be attached to document. For more information please see this.

Upvotes: 2

RAHUL S R
RAHUL S R

Reputation: 1579

you can try ajaxStart

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

Upvotes: 1

Related Questions