views:

60

answers:

2

I'm using ASP.NET MVC. So I have a form on my page:

<form id="MyForm" name="MyForm" method="post" action="http://www.mysite.com"&gt;
    <input id="hdnType" name="hdnType" type="hidden" />
</form>

I'm using the jQuery submit action to do some validation before the form is posted. I also need to make an AJAX call to set "hdnType" based on other values from several dropdowns that I didn't include in this example:

$('#MyForm').submit(function()
{
    if (!ValidForm())
        return false;

    $.ajax({
        type: "POST",
        url: '/Home/GetType',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response)
        {
            $('#hdnType').val(response);
        }
    });

    return true;
}

Everything in the submit() function is supposed to run before the form posts. This was working correctly before I added that AJAX call, but now when the code reaches my AJAX call, the form posts before I can set "hdnType".

Is there a way around this?

+1  A: 

The success function is called asynchronously, after the ajax call gets a response. If you want to set hdnType before the form is posted you'd have to move that call outside the $.ajax call. It looks like you need to get the result for hdnType from your POST action first, in a separate function, then call submit on the form.

Dave Swersky
+2  A: 

The ajax call has a parameter async. By default it is true. This causes execution to not be held and the function to complete. Try changing it to

$.ajax({
    async:false,
    type: "POST",
    url: '/Home/GetType',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response)
    {
        $('#hdnType').val(response);
    }
});

This may be a poor practice as it will freeze the browser until it is done. Consider using an asyc call back function as Dave suggests

Andrey
Nice, I didn't know I could do that. Thanks.
Steven