Friday, October 12, 2012

jQuery Ajax request progress events Example


jQuery provides 2 events ajaxStart and ajaxEnd, which will get fired when an Ajax request starts and when the request Ends, these events can be used to display a loading information to the user.

In this post we shall see on how to use the jQuery Ajax progress indicator events ajaxStart and ajaxEnd to display the status of an Ajax request.

We will make a call to the server which will be time consuming and see on how these events show a loading message till the request is completed.

Add the following code to a page, and click on the Show Progress button.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Ajax Handlers</title>
<script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
    <script
        type="text/javascript"
        language="javascript">
        $(document).ready(function() {
            //
            // Load Data
            $('#btnProgress').click(function(event) {
                event.preventDefault();
                var nameList = "";
                $.ajax({
                    url: "AjaxData.aspx",
                    data: { ID: "2" },
                    cache: false,
                    dataType: "xml",
                    success: function(result) {
                        $(result).find("Name").each(function() {
                            nameList = nameList + $(this).text() + "<br />";
                        });
                        $("#divProgress").html(nameList);
                    }
                });
            });
            //
            // Progress Indiator
            $("#divProgress").ajaxStart(function() {
                $("#divProgress").html("Loading.. Please wait");
            });
            //
            $("#divProgress").ajaxStop(function() {
               
            });                                   
        });
    </script>                 
</head>
<body>
    <form id="AjaxHandlers" runat="server">
        <table border="1">
            <tr>
                <td><b>Action</b></td>
                <td><b>Response</b></td>
            </tr>
            <tr valign="middle">
                <td>
                    <asp:Button
                        ID="btnProgress"
                        runat="server"
                        Text="Show Progress" />
                </td>
                <td align="center">
                    <br /><div id="divProgress"></div> 
                </td>
            </tr>                    
        </table>       
    </form>
</body>
</html>

We will mandate a delay in the server side, to see the loading indicator, on clicking the Show progress button the ajaxStart event gets fired and sets a loading message in the DIV tag, once the request is processed the loading message is replaced with the data from the server.

Related Post



Search Flipkart Products:
Flipkart.com

No comments: