Showing posts with label javascript. Show all posts
Showing posts with label javascript. 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 !!!

How to print contents of Div only

Generally we do not want to create complex report and our clients are not interested in purchasing expensive reporting tools then we can generate simple HTML based reports for them. You just have to place your report inside a< div>... < / div> and you can easily print that. Here is a sample through which you can easily print contents of specified div only:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML; 
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;
            
            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
            
            //Print Page
            window.print();
            
            //Restore orignal HTML
            document.body.innerHTML = oldPage;
            
            //disable postback on print button
            return false;
        }
    </script>
    <title>Div Printing Test Application by Zeeshan Umar</title>
</head>
<body>
    <form runat="server">
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return printDiv('div_print');" />
    <div id="garbage1">I am not going to be print</div>
    <div id="div_print"><h1 style="color: Red">Only Zeeshan Umar loves Asp.Net will be printed :D</h1></div>
    <div id="garbage2">I am not going to be print</div>
    </form>
</body>


Here is the output of the page when I run the code:-



And when I pressed print button, it hide all the remaining area and only my div's contents are visible which will be printed:-


Feel free to comment if you require any clarification. Happy coding !!!

How to prevent cache issue with Images, CSS and Java scripts, a better aproach

Generally when we update images, CSS or java script (.js) files on server, browser still shows old files. This is because in first request, browser download all images, CSS and .js files. But on subsequent requests, browser load images, CSS and .js files from its cache. Here is the solution which you might found on most of blogs i.e. add a DateTime.Now.Ticks as parameter after file name like this:-
<img src='PTCL-3.jpg?websiteversion=<%=DateTime.Now.Ticks.ToString()%>' alt="Sample Image" />

This will solve your problem and you will always get updated images. But the problem with this approach is that your images, CSS and java script will be downloaded for every request which will slowdown your site's performance.

Now, here is how you can solve both the problems, Add a key in appSettings section of your wen.config file like this:-
<appSettings>
    <add key="WebsiteVersion" value="1"/>
</appSettings>

And add the parameter to your images, CSS and java script files like this:-
<img src='PTCL-3.jpg?websiteversion=<%=System.Configuration.ConfigurationSettings.AppSettings["WebsiteVersion"] %>' alt="Sample Image" />

Now whenever you change any Image, CSS or .js file you have to update the WebsiteVerion value in your web.config file.

Do share your comments, happy coding !!!

How to Pass value from ASP.Net to Javascript

Many times we have to pass a value from server side (ASP.Net) to client side (java script) and many peoples ask this question that how we can accomplish this task. Here I am sharing some examples in which I will tell different approaches to send values from ASP.Net to javascript.

1- <%=%> Construct
You can simply use a <%=%> construct to pass server side variable to client side. Here is how you can do this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var myVariable = '<%=ServerSideVariable %>';
    alert(myVariable);
</script>

Here is the server side code in which I assigned value to my variable:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    public string ServerSideVariable { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        ServerSideVariable = "Zeeshan Umar";
    }
}

Here is the output when I run the page, a popup appears saying 'Zeeshan Umar'.

2) Hidden Field
You can also use hidden fields to store values which can be used in javascript here is how you can do this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="hfValueFromServer" runat="server" />
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var valueFromServer= document.getElementById('<%=hfValueFromServer.ClientID%>').value;
    alert(valueFromServer);
</script>

Here is the server side code in which I assigned value to hidden field:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        hfValueFromServer.Value = "Zeeshan Umar javascript tutorial";
    }
}

And here is the output of above code, same as expected 'Zeeshan Umar javascript tutorial':-

See how simple is it to access server side variables in javascript. Do share me with your valuable feedback and comments. Happy coding !!

How to end session when browser is closed

In high traffic sites sessions are very costly and they use lots of server's memory. Generally session timeout is 20 min (by default) and even if user closes the browser. Values in session still exist until session get expired after timeout. We can save lots of server memory if we destroy session as user closes the browser.

Here is how you can do it:-

1)First create a page AutoLogOut.aspx and in Page_Load event write this code:-
protected void Page_Load(object sender, EventArgs e)
{
    Session.Abandon();
}

2- Then add following javascript code in your page or Master Page:-
<script type="text/javascript">
     var clicked = false;
    function CheckBrowser()
    {
        if (clicked == false)
        {
            //Browser closed
        }
        else
        {
            //redirected 
            clicked = false;
        }
    }
 
    function bodyUnload()
    {
        if (clicked == false)//browser is closed
        {
            var request = GetRequest();
            
            request.open("GET""AutoLogOut.aspx"true);
            request.send();
        }
    }
 
    function GetRequest()
    {
        var request = null;
        if (window.XMLHttpRequest)
        {
            //incase of IE7,FF, Opera and Safari browser
            request = new XMLHttpRequest();
        }
        else
        {
            //for old browser like IE 6.x and IE 5.x
            request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        return request;
    } 

3- Finally on your body tag add these event handlers:-
<body onunload="bodyUnload();" onclick ="clicked=true;>

Now when user closes the browser, it will close session on server. However I just like to highlight that this solution might not work 100% time as there are chances that when user close the browser, he is not connected to internet.

Feel free to share your comments on my post.

How to keep session alive in ASP.Net using Webservice and jQuery

Most of the time when we develop intranet web applications, our clients request us that they only have to log in in the morning when they reach office. It seems very easy to implement i.e. increase session timeout to 10+ hours and we are done.

But there is a drawback of this approach. Even if user close the browser, session's data will occupy server's memory till 10+ hours and our site's performance will go down. So, this is certainly not a good choice for us.

There are many alternates to solve above problem. In this post, I am sharing one of the possible solution.

First I have created an asmx service i.e. SessionAlive:-

/// <summary>
    /// Summary description for SessionAlive
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class SessionAlive : System.Web.Services.WebService
    {
 
        [WebMethod]
        public void UpdateSession()
        {
            HttpContext.Current.Session["tempVariable"] = DateTime.Now;
        }
    }

Note that by default [System.Web.Script.Services.ScriptService] is commented when you create a new service. You need to uncomment above line to ensure that methods in this service are accessible for javascript or jQuery.

Also i have created UpdateSession() method which updates a value in session.

Now here is the javascript which I added in my page.

<script type="text/javascript" src="JS/jquery-1.4.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        setTimeout(updateSession, 1000*60);//Timeout is 1 min
    });
    
    function updateSession() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "SessionAlive.asmx/UpdateSession",
            data: "{}",
            dataType: "json"
        });
        setTimeout(updateSession, 1000 * 60);
    }
</script>

Above function calls web service after every minute to ensure that session is not time out. Hopefully this will be useful for you. Feel free to add comments and suggestions.

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.

How do disable back button in browser

Generally there are cases when we want to disable back button in browser. We have multiple options to disable back button in browser. Here are the few:-

Java Script Way
We can use following java script to prevent back button:-
<script type = "text/javascript" >
function disableBackButton()
{ 
window.history.forward();
}
setTimeout("disableBackButton()", 0);
window.onunload=function()
{
null
};
</script>

HTML Way
We can also add Meta Tags in Head Section like this:-
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

If you want to do above approach through code. Here is the trick:-

HtmlMeta pragma = new HtmlMeta();

pragma.HttpEquiv = "Pragma";

pragma.Content = "no-cache";

Page.Header.Controls.Add(pragma);

 

HtmlMeta expires = new HtmlMeta();

expires.HttpEquiv = "Expires";

expires.Content = "-1";

Page.Header.Controls.Add(expires);


ASP.Net Way
In ASP.Net we can use Cache to disable back button like this:-

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

Response.Cache.SetNoStore();

Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

How to add a confirmation on Button Click


Here is the code how you can add a client side confirmation box on button click :-
<asp:Button ID="btnDelete" runat="server" Text="Delete" 
OnClientClick="return confirm('Do You Want to Delete Record');"/>