简体   繁体   中英

Block user interaction while doing ajax call using javascript

I have a form with a button to generate a document. While generating document asynchronously, I want to stop any user interaction (click the button, input text, etc) until the process is done.

I've ever used BlockUI, but this time, I want to know another way without BlockUI.

How this can be done using javascript or jquery? I'm using ASP.NET MVC to create this form.

View

@using (Ajax.BeginForm("Generate", new AjaxOptions 
    {
        LoadingElementId = "progress",
        UpdateTargetId = "result"
    }))
{
        @Html.DropDownListFor(model => model.ID, new SelectList(Model.Employees, "Value", "Text"), htmlAttributes: new { @class = "form-control" })
        @Html.DropDownListFor(model => model.Template, new SelectList(Model.Templates, "Value", "Text"), htmlAttributes: new { @class = "form-control" })
        <button type="submit" class="btn btn-success">Generate</button>

        <span id="progress" style="display:none;">
            <img src="@Url.Content("~/Content/Images/busy.gif") ">
        </span>

        <span id="result"></span>
}

You can just add some CSS for your spinner container. Like this

html, body {
    height: 100%;
    z-index: 1;
}

#progress {
    background: rgba(0, 0, 0, .7);
    display: block;
    height: 100%;
    left: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 10000;
}

It will stretch your container with spinner image all over web page and block user clicks.

You could use ajaxStart and display a loading-bar, making everything behind inaccessible.

$(document).ajaxStart(function () {
    $('#ajaxContainer').show();
});
$(document).ajaxComplete(function () {
    $('#ajaxContainer').hide();
});

This is code I used in _Layout.cshtml, where #ajaxContainer is a div containing img loading-bar

I do not know if it works with @Ajax.BeginForm, but it works great with jQuery $.ajax. If it does not work with @Ajax.BeginForm you can always use jQuery $.ajax

EDIT: #ajaxContainer looks like this:

<div id="ajaxContainer" style="display: none">
    <div class="loaderdiv">
        <div class="loader">
            <img src="~/Images/ajax-loader.gif" alt="" />
            <br />
            <span class="loader-text">Loading...</span>
        </div>
    </div>
</div>

You may want synchronous ajax call.

$.ajax({
    …
    async: false,
    …
});

More about $.ajax

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM