Advertisements

Archive

Archive for the ‘Javascript’ Category

How to refresh page using javascript freaquently and automatically ?

July 25, 2011 2 comments

Refresh web page using javascript with regular intervals

In some scenario, we need to refresh our web page automatically with some interval of time. The better method to do it is using Javascript function. Then we can set a time interval period and for each interval time page will be refresh without any user interaction with web page.

Using setTimeout() with Javascript

The Javascript setTimeout() function allows code to be executed a set of time after some trigger, such as when the page has loaded or a button is pressed.  That means, the setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Syntax of SetTimeOut() in Javascript

setTimeout(code,millisec,lang)

Examples of setTimeout() with Javascript

A simple example of setTimeout() in javascript, below sample function shows alert message with the time interval 3 seconds after click the button.

<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('I am displayed after 3 seconds!')",3000)
}
</script>
</head>
<body>

<form>
<input type="button" value="Display timed alertbox!" onclick="timedMsg()" />
</form>

</body>
</html>
 

Below mentioned example of setTimeout() in Jvascript will start count down after click the button up to the seconds that we enterd into the text box. It is very simple sample for setTimout(0 in javasscript can be easily understood by beginners also.

 

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
</script>
</head>
 

How to reload web page frequently and automatically using javascript setTimeout() function? Below mentioned function will help to refresh page frequently with the time of interval that we mentioned.  We can done it by two methods

  1. In meta tage we can set time of interval and have to also mention url that we have to load with the time of interval.
<meta http-equiv="refresh" content="30;url=index.html">
  1. 2.  Next option is create a method in javascript and call it in page load as mentioned below.  
<script type="text/javascript">
    window.onload = setupRefresh;

    function setupRefresh() {
      setTimeout("refreshPage();", 30000); // milliseconds
    }
    function refreshPage() {
       window.location = location.href;
    }
  </script>
Advertisements

How to access URL or URL parts using javascript / Get the Website URL using JavaScript

July 14, 2011 20 comments

How To Get URL Parts in JavaScript :: A JavaScript Tutorial For Beginners

In some scenario we need to communicate with website url that seen in address bar of the browser using JavaScript. It’s very easy to access the url using javascript. But in order to get query string from URL, default functions or methods are not available. Using javscript we can access the URL using default method in javascript. We are not able to edit URL in javascript without postback. But we can reload the page from javascript and also we can redirect to other url from javascript. Let’s see all about jaavscript with website URL.

How to get website URL in JavaScript / how do I use javascript to get url of current page

Here we are going to explain how we can use javascript to get the website url of the current page. Lets imagine our current page is http://myexample.com/example/index.html and we need to get each part of the url separately in javascript. We can access the parts of URL using javascript as follows.

window.location.protocol = "http"
window.location.host = " myexample.com "
window.location.pathname = "example/index.html"
window.location.href = "http://myexample.com/example/index.html"

If we want to access the entire website URL of the current page we can use window.location.href as mentioned above. Also we can access part by part of current page URL in javascript using above mentioned options. But there is no default option to get/access the query string values in current page URL in javascript.

 Redirect to another page using JavScript/ JavaScript redirect to a new page

 By using window.location we can redirect to another website page from javascript. So it’s better to use javascript navigation to redirect to another page instead of asp.net response.redirect function. Because Response.Redirect function first send to Server then identifying the web page that we need to navigate and again resend to client. There is a extra round trips will be happen in the case of Response.Redirect method. To avoid this round trips we can use Javascript redirection method as follows.

           window.location = “http://www.supershope.com&#8221;;

 How to access/get query string values in website URL using JavaScript (from client side)

 In order to access the querystring  of the current web page there are no default functions or methods in JavaScript.  To get URL parameters using javascript we are demonstrating a function that is used to get all the URL parameters from website in JavaScript.

 Javascript function to get all URL parameters from Website URL

 function getUrlParams() {
    var params = {};
    window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function (str, key, value) {
    params[key] = value;
});
    return params;
}

 var params = getUrlParams();

alert(params.id);

alert(params.name);

 Whenever we want to get querystring values from website URL we can call above function and which returns a object that holds all website URL parameters of the current page as key value pairs.

 How to get a particular querystring value from the URL in JavaScript

 We have noted that we cannot able to get query string from website URL in default methods in JavaScript. So we written a function to get all parameter values in the current page. But if we want to get a particular querystring values from the URL it’s difficult to use above method. That means if I want to get ‘id’ query string from the URL we need to get all parameters from the URL and from that collection get id values. Instead of this we are going to write another function which access the URL parameter name as the function parameter and return value of the particular querystring. If there is no query string in the URL with specified name will return empty string.

 Javascript function to get particular querystring value from the website URL

 function getParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
 
var id = getParam('id');
alert(id);
 

By using above function, we can easily get particular query string from client side script. If we send a value to above function and suppose there is no query string with that name, then it will return empty string. Hence we can easily accessing query string from client side using JavaScript.

How to call serverside function from client side javascript in ASP.Net?

June 10, 2011 26 comments

Call ASP.Net/C# function using Javscript

Usually in ASP.net platform, server side functions (all codes written in asp.net,C#) are executing from the server side and all client side funtions (javascript,jquery,ajax) are executing from the client side. Obviously client side functions are too faster than the server side because there is no need to go upto server, will running from the browser itself.

But we are unable to written all functions in client side to get good performance. But for this technique, there is some tips can be used. What we are going to do is, we are writing a server side code in ASP.Net,C# and call these functions from client side using javascript and ajax.

Steps to Calling ServerSide method from javscript

  1. Create a aspx page with three textboxes and a button control.
  2. User enter two numbers in first two textboxes and press calculate button.
  3. We are fetching entered values and calling a serverside funtion by passing this values.
  4. In the server side function find the sum and return the result.
  5. In client side’s succes event, getting result from the server and displayed to third textbox.

Step 1 :

 Create a aspx page with controls, two textboxes for entering the numbers, one button for find the sum of number and a one more text box to display the result.

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Result.aspx.cs" Inherits="testWebApp.Result" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!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">
      <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
        <table>
            <tr>
                <td>
                    Number1:
                </td>
                <td>
                    <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Number2:
                </td>
                <td>
                    <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Sum:
                </td>
                <td>
                    <asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSum" runat="server" Text="Sum" OnClientClick="CallSum();return false;" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Step 2  

In code behind, write a web method to access two parameters and return the result. In the function we added parameters and return the result.

protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Server side function Sum
        /// </summary>
        /// <param name="arg1">arg1</param>
        /// <param name="arg2">arg2</param>
        /// <returns>result(sum)</returns>
        [System.Web.Services.WebMethod]
        public static int Sum(int arg1, int arg2)
        {

            /* On server side we can do any thing. Like we can access the Session.
             * We can do database access operation. Without postback.
             */
            try
            {
                return arg1 + arg2;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Step 3

 Create a javscript method in aspx page to get input textboxes values and call serverside function. Here itself we decalre a success and failure event, for getting the event from the server after the current function executed.

 <script language="javascript" type="text/javascript">
    <!--

        // Javascript function
        function CallSum() {
            //Get the controls
            var txt1 = $get("txt1");
            var txt2 = $get("txt2");
            var txtresult = $get("txtSum");

            //Call server side function
            PageMethods.Sum(txt1.value, txt2.value, OnCallSumComplete, OnCallSumError, txtresult);

            /*Server side function get the 2 arguments arg1 and arg2. We are passing txt1.value and txt2.value
            for that. OnCallSumComplete is callback function for complete successfully. OnCallSumError is callback
            function on error. txtresult is usercontext parameter.

            OnCallSumComplete,OnCallSumError,txtresult are optional parameters.

            If server side code executed successfully then OnCallSumComplete will call.
            If server side code do not executed successfully then OnCallSumError will call.

            */
        }

        // Callback function on complete
        // First argument is always "result" if server side code returns void then this value will be null
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumComplete(result, txtresult, methodName) {
            //Show the result in txtresult
            txtresult.value = result;
        }

        // Callback function on error
        // Callback function on complete
        // First argument is always "error" if server side code throws any exception
        // Second argument is usercontext control pass at the time of call
        // Third argument is methodName (server side function name) In this example the methodName will be "Sum"
        function OnCallSumError(error, userContext, methodName) {
            if (error !== null) {
                alert(error.get_message());
            }
        }

    // -->
    </script>

Project is ready for call server sided functions from client side using javascript. Run the application and enter two numbers in first and second textboxes then press calculate button, the we can show that result is displayed in third box without any page postback. If we enterd alphabets instead of numbers, from the server it will happening error and ‘failure’ event occurred in the javascript will alert the details of the error.

How to confirm before close browser using javascript?

June 1, 2011 1 comment

Can we stop browser close using Javascript? 

Some time it’s better to give a warning to user when he trying to close the browser. Some browsers has the facility by default but they can be disabling from the browser itself. So it’s better to give a warning message to user from the application itself. In this case we can use JavaScript for given the confirm message to user before close the browser window.

 How to stop browser closing using javscript ?

We have to call a javascript funtion to give a confirmation message to user on browser closing event. We can achieve it by call a event ‘onbeforeunload’ from the body tag. This event will fired when a user close the browser. On this event we are calling a function quit(), On this function we are given a confirm message to user and return the result. If user clicks OK browser will close, if user press cancel it will return to the browser

 Simple Javascript codes to prevent browser close

 
<html>
<head>
<script type="text/javascript">
function quit(){
event.returnValue="Are you sure you have finished?"
}
</script>
</head>
<body onbeforeunload="quit()">
<div id="timeDiv"></div>
</body>
</html>
Categories: Javascript Tags:

How to display current time using javascript?


How ro create a Javascript clock?

Most of the websites are shown current time on top or bottom. But if we want to display updated time that means updated by each seconds, we can implemented JavaScript timer for the same. In some of the case we need to display count time or stopwatch have to display on our website, that time also we can implement same technique.

 Javascript code for dynamic timer.

Below are the javascript codes for timer. There is a default function setTimeout available in javscript for repeated execution for a particular period.

 
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('timeDiv').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',00);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
</head>

<body onload="startTime()" bgcolor="blue">
<div id="timeDiv"></div>
</body>
</html>

%d bloggers like this: