开发者

AJAX call in jQuery form submit function

开发者 https://www.devze.com 2023-01-19 06:41 出处:网络
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\">

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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号