In this article I will explain how to disable controls when an Ajax call is ongoing. This will prevent users from making more than 1 click on controls.
Consider a situation when a user logs in to a website. He/she enters the username and password and then clicks the Submit button. The HTML code of the control is given below.
I have a “content” div which contains a “table”. The “table” contains “Username” & “Password” input controls along with a “submitButton”.
After the table, there is an “img” control that will show the loading image during AJAX call. I have also kept a “messageDiv” that will show the message when a user gets logged in to the website.
NoteMy aim here is to disable the “username” & “password” input controls and also, the button control when AJAX call is made. I will also show the loading image over the center of the “Content” div during AJAX calls.
The CSS which you have to add to this page is mentioned below.
NoteTo show the image at the center of “content” div, first, set the position of the “content” div to "relative". Then, for the image, set its position to "absolute", margin to "auto", and “top,left,right & bottom” properties to 0.
Initially, the image will remain hidden but when AJAX call starts, it will be shown. Similarly, on completion of the AJAX call, the image will again be hidden.
On the button click, the AJAX call will be made using .ajax() method. The jQuery code for this is as follows.
The .ajaxStart() method will be called when the AJAX call starts while .ajaxStop() method is called when the AJAX call has returned some value.
Inside in the .ajaxStart() method, I am setting the background of the table to grey color and disabling all the input controls (2 textboxes and 1 button). I am also showing the image control which will show in the middle of the “content” div (check its CSS).Note - You can also do the AJAX call using jQuery Post method. The .ajaxStart() & .ajaxStop() methods will work the same way.
Similarly, in the .ajaxStop() method, I am hiding both the table and the image. If you check the jQuery AJAX code under the button click event, you will see that I have called the C# function named “login” and passing to it the 2 textboxes values.
This C# login function will get the username and password values, then it checks them against the database stored login and passwords. If it finds them on the database table, the user is logged in.
Run the page in the browser, enter any value for username and password, and click the Login button. The loading image will show in the middle of the “content” div and the input controls will be disabled.
After 2 seconds (approximately), when AJAX call completes, both, the image and the table, are hidden.
Pro WPF: Windows Presentation Foundation in .NET 3.0