Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

$(document).ready(), pageLoad() and Sys.Application.add_init()

When I have basic understanding of AJAX and jQuery, I thought that $(document).ready(), pageLoad() and Sys.Application.add_init() are equivalent and they does the same job. In most of the samples they seems to behave in same way and I wondered that why there are too many ways to do the same thing. So I did bit research on this and I am sharing that with the developer community.

jQuery's $(document).ready()
This function is called when DOM is ready. Generally if browser supports DOMContentLoaded event, $(document).ready() will fire after this event. If browser do not support DOMContentLoaded, then when document achieve readyState, then $(document).ready() will be fired. If above two events are not available in Brower's event model then window.onload event is used to fire $(document).ready() event.

If you are using jQuery, then my No. 1 recommendation is this function as this will work on
all browsers. Here is a sample how you can use this function:-
$(document).ready(function () {
//Your code here
});

Application.Init
This event is fired only once when page is loaded first time. Remember, that if you are using update panel then this method will not be called whenever update panel refresh your page. So, this is best event when you want initialization which should be done only once and not after every update panel refresh.
<script type="text/javascript">
    Sys.Application.add_init(function () {
        // Your code here
    }); 
script>

ASP.NET AJAX's pageLoad() Method
As we all know java scripts runs as a single thread, pageLoad method uses a trick, it calls a setTimeout() function of JavaScript with 0. So, whenever DOM is ready and JavaScript execution is started, you  pageLoad() will be triggered.

Now, use this method when you want to call your code every time when your update panel gets refresh.
<script type="text/javascript">
    function pageLoad() {
        // Your code here 
    } 
script>
 
Note that to use AJAX methods you need to place ScriptManager object on  your page other wise they won't work.

Feel free to comment, Happy Coding !!!

PageMethod an easier and faster approach for Asp.Net AJAX

We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:-

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

Here is how my Page looks like:-


To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true. This will tell ScriptManager that I am going to call Page Methods from client side.

Now Next step is to Create a Server Side function. Here is the function which I created, this function validates user's input:-


[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
 
    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password canonot be less than 5 chars";
    }
 
    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things. First this method should be 'public static'. Second there should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:-

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods. My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>


Finally I have pressed Signup button and I am geting these messages.

See it is really simple. Now there is a fair chance that instead of these fancy looking messages you might be getting this error:-

If you see error like this then double check following things:-
  1. You have set EnablePageMethods="true" in ScriptManager.
  2. You have added [WebMethod] tag in your server side method.
  3. Your server side method is 'public static'

Hopefully this will be useful for you feel free to share your comments and suggestions.