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">
    <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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.