Simple Ajax Request – Loading a Text File

0 comments

        Before starting the tutorial just a look into “what is Ajax ?”. Ajax is nor a programming language neither it is a framework, instead it is a technique used to develop Rich Internet Applications, i.e. applications which are more faster, more graphical and more interactive. AJAX (Asynchronous Javascript and XML) is a combination of several existing technologies rather than being a single technology.

       Here are the basic technologies involved in Ajax applications:
• HTML is used to build Web forms and identify fields for use in the rest of your application.
• JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.
• DHTML, or Dynamic HTML, is used to update your forms dynamically. You'll use div, span, and other dynamic HTML elements to mark up your HTML.
• Server Side Scripting is used to process the query passed by Javascript and returns the response XML.

       Thus with AJAX, a JavaScript can communicate directly with the server(with a XMLHttpRequest object) and transfer data with it asynchronously, i.e. without submitting or reloading the page.

       The XMLHttpRequest object is the key component to Ajax that makes it so useful. It provides a mechanism for the client (through Javascript) to send information to the server and receive a response as XML. The response XML can be processed in the background and used to dynamically update elements on the page. In effect, information flows, and screens are updated, more like in desktop applications than in old-fashioned web applications.

       Now lets move to the coding part. Basic AJAX is normally composed of three JavaScript functions:
1. A function that creates an XMLHttpRequest object
2. A function that calls the XMLHttpRequest object and submits it,
3. A function that handles the information sent back to the page.

       Lets look at the first function. We first declare a variable with name xmlHttp. Now depending upon the browser an ‘xmlHttpRequest’ object is created and assigned to this variable. If the browser is Internet Explorer, then we have to create a new ‘ActiveX Object’ and if the browser is Firefox,Opera etc, then we have to create a new ‘xmlHttpRequest’ which is a built in object. The function then returns the just constructed object.
function getXMLHttp()
{
   var xmlhttp;
   if (window.ActiveXObject)
   {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   else if (window.XMLHttpRequest)
   {
      xmlhttp = new XMLHttpRequest();
   }
   else
   {
      alert("Your browser does not support Ajax!");
   }
   return xmlhttp;
}
       In the second function we use the first function to create an xmlHttpRequest object and open an HTTP connection using it. We pass three parameters in the xmlHttp.Open() function. First is the submit method (it can be POST or GET). Second is the URL ,which contains the serve side processing (here to make it simple we are using a text file) and which returns the result to the script as xml. Third is a boolean value which states whether the transfer is asynchronus(true) or synchronus(false). Next we call a function when the ready state changes(loaded, loading, not loaded). Next we send a null to the other page (may not be null for POST , but always null for GET).
function getTextInfo()
{
   xmlhttp1=getXMLHttp();
   var url =”"demo1.txt” ;
   xmlhttp1.open("GET",url,true);
   xmlhttp1.onreadystatechange = updateInfo;
   xmlhttp1.send(null);
}
       In the ‘readyStateChange’unction we first check whether the reponse is loaded (whether state is 4). The content of the text file is transferred as reponse text. We get the content into a variable and display it to a textarea/div.
function updateInfo()
{
   if(xmlhttp1.readyState == 4)
  { 
     var response=xmlhttp1.responseText;
     document.getElementById("showText").value = response;
   }
}
This sums up the tutorial. Hope this was useful for you.
You can find the entire code along with html from here.
Please enter your valuable comments and suggestions.

City World Clock - based on Timezone

0 comments

        This javascript code snippet allows you to display the time of a city, selected from a drop-down. It also loads the current time and location as the default time and location (based on computer’s timezone and entry in dropdown list). The script is mostly similar to the previous post.

        Here also we have 2 divs for displaying time and date, and a select drop-down for selecting city. We are also using the ‘calculateZoneTime()’ function for calculating time. Also we have slightly modified ‘returnFormattedDate()’ and ‘returnFormattedTime()’ functions for formatting date and time respectively. The time is updated every second using the ‘init()’ function. The ‘init()’ function calls the ‘calculateZoneTime()’ function and repeats itself using the setInterval function.

        An additional function is ‘calculateDefaultTimeZone()’ which is used for calculating the computer’s current timezone and setting the html select to that particular timezone on page load.
function calculateDefaultTimeZone()
{
      var newDate = new Date();
      // finding current timezone – received in decimal format
      var timeOffset = (newDate.getTimezoneOffset()/60) * (-1);
      var timeZone1 = document.getElementById('selectTZ1');
      // converting decimal format to “hh:mm” format
      var formattedOffset = formatTimeOffset(timeOffset);
       
      if (timeZone1)
     {
           // finding the current timezone in select drop-down
           for (var i = 0; i < timeZone1.options.length; i++)
          {
              if (timeZone1.options[i].value == formattedOffset)
             {
                 timeZone1.selectedIndex = i;
                 break;
            }
      }
  }
}
        The ‘formatTimeOffset()’ function converts the calculated current time zone from a decimal format to a  “+/-hh:mm”  format. Here is the function code:
function formatTimeOffset(value)
{
    var hours = parseInt(value);
    value -= parseInt(value);
    value *= 60;
    var mins = Math.abs(parseInt(value));
    var display_hours = hours;   
    var display_mins = (mins < 10) ? ("0" + mins) : mins;
    timeZoneString = display_hours + ":" + display_mins;
    return timeZoneString;
}
Hope this is helpful to you.
You can find the entire code along with html from here.
Please enter your valuable comments and suggestions.

World Clock - based on Timezone

0 comments

        This javascript code allows you to display the time based on the user’s timezone. The script makes use of the inbuilt javascript ‘Date’ object and its functions. The clock displays time in the default 12 hour format, that can be changed to a 24 hours using a radio button. Also we are displaying the current day and date. The user can also change the timezone using a select box, and thus can view the current time in different timezones.

        First lets have a look at the form. The form consists of two div elements, one for displaying time and the other for displaying day and date. There is a select element (selectTZ) which consists of all time-zones.
<div name="timeText" id="timeText"></div>
<div name="dayText" id="dayText"></div>
<select name='selectTZ' id='selectTZ'>
    <option value='0'>Select your Timezone</option>
    <option value='-12:00'>(-12:00) International Date Line West</option>
    <option value='-11:00'>(-11:00) Midway Island, Samoa</option>
          ……………….
</select>
        Now lets start with the javascript code. First we have to retrieve the current date and time. The following line of code do this.
// create new date object
  var time =  new Date();
  // get the formatted date value
  var dayText = returnFormattedDate(time);
  // get the formatted time value (hh:mm:ss or hh:mm:ss pm/am))
  var timeText =  returnFormattedTime(time);
  // passing formatted value to divs
  document.getElementById("timeText").innerText=timeText;    
  document.getElementById("dayText").innerText=dayText;

        The ‘returnFormattedDate()’ and ‘returnFormattedTime()’ functions return the date and time respectively in a specific format. ‘returnFormattedDate()’ returns date in “Monday, 01 January 2010” format. Whereas, ‘returnFormattedTime()’ returns time in any of the two formats, “23:45:06” or “11:45:06 pm”.
       The above code can be modified for using time-zones as follows.
function calculateZoneTime(SelectTimeZone)
{
     // if timezone not selected
    if(SelectTimeZone=='0')
    {
        document.getElementById("timeText").innerText="00 : 00 : 00";
        document.getElementById("dayText").innerText= "please select a timezone";
        return true;
    }
    // get current date object
    var zDate = new Date();
    //  retrieve offset of the selected timezone in decimal format
    var ZoneOffset = retrieveOffset(SelectTimeZone);
    // adding the time difference to current time (in milliseconds)
    var ms = zDate.getTime() + (zDate.getTimezoneOffset() * 60000) + ZoneOffset * 3600000;
    // creating a date object using the calculated zone time
    var time =  new Date(ms);
    var dayText = returnFormattedDate(time);
    var timeText =  returnFormattedTime(time);
    document.getElementById("timeText").innerText=timeText;
    document.getElementById("dayText").innerText=dayText;
}
         Here the function parameter ‘SelectTimeZone’ is the value of the time-zone that is selected in the ‘selectTZ’ select. The ‘retieveOffset()’ function converts the parameter value from the “4:30” format to a “4.5” format, so that it can be used for date calculations. This offset is then added to the current time, to get the time-zone specific time.

        The code for ‘retieveOffset()’ is as follows:
function retrieveOffset(TimeZoneOffset)
{
      try
      {
         // calculating the whole and decimal part of the offset
         var timeArray = TimeZoneOffset.split(":");
         var hrs = parseInt(timeArray[0]);
         var mins = parseInt(timeArray[1])/60;
       }
      catch(err){  alert("error"); }
     // adding or deleting the decimal part and whole part
      var offset = (hrs > 0) ? (hrs + mins) : (hrs - mins);
      return offset; 
}
        Now we have to update the time every second. For this we have a ‘init()’ function. The function calls the ‘calculateZoneTime()’ function and repeats itself using the setInterval function.
function init()
{
     try
     {
             // try to clear any interval previously set
              clearInterval(myInterval);
     }
     catch(err){}
     // calculate time based on select value
     calculateZoneTime(document.getElementById("selectTZ").value) ;
     // repeat the init function each sec (1000ms = 1 sec)
     myInterval = setInterval("init()",1000);    
}
        This sums up the article. Hope this helps. This post is open for your queries and suggestions.
You can find the code (with HTML) in its entirety here. Also you can find an advanced version of the script that loads the current time zone as default on the clock, here.

Set as Homepage, Bookmark a page

0 comments

The following javascript code snippet allows a user to add your page as homepage, and to bookmark (favorite) your page.

The following javascript function code allows you to add the current address location as the Homepage of your browser.
function setHome()
{
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage(window.location.href);
}
The following javascript function code adds the current address location to your browser’s Bookmarks list, and the document title is set as the title (name) of the Bookmark.
function setBookmark()
{
var title = document.title;
var address = window.location.href;
if(window.sidebar)
{
window.sidebar.addPanel(title,address);
}
else if(window.external)
{
window.external.AddFavorite(address,title);
}
else if(window.opera && window.print)
{
var elem = document.createElement('a');
elem.setAttribute('href',address);
elem.setAttribute('title',title);
elem.setAttribute('rel','sidebar');
elem.click();
}
}
The problem with the above codes is that the ‘Homepage’ code works only in Internet Explorer, and the ‘Bookmark’ code is somewhat erry in Firefox (bookmarked page opens in sidebar).
But there is another option available though not javascript. The addthis site provides you with a custom button that can be added to your site/blog, that not only allows to bookmark your page but also provides you with data related to how and where the content is being shared.

You can download the entire code from here.

Show div once a day using Javascript

0 comments

The following javascript snippet allows you to show a message to the user who visits the page for the first time, and hides the message if he makes subsequent visits to that page on that day. The script involves cookies and thus need to have cookie-enabled in the user browser.

First lets have a look at the form. The form consists of a single ‘div’ element. The message to be displayed has to be kept inside this div. It can be text or image or any other display content.
<form name=”scriptDen”>
<div id="myDiv"> Place Your Content Here </div>
</form>
Next we have to build the code for creating a cookie. This cookie has to be created when the user visits the page for the first time. The createCookie() function takes name of the cookie, its value and its expiry period(in days) as parameters. Since we are creating a cookie for a day, the expiry period will be one.
function createCookie(name,value,days)
{
   // new Date object created
   var date = new Date();
   // adding days to current time
   date.setTime(date.getTime()+(days*24*60*60*1000));
   // converting to standard format
   var expires = date.toGMTString();
   // adding cookie name,value and expiry time
   document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
Now we need to read the cookies stored in the browser and look whether our cookie is present there or not. The readCookie() function returns true if the cookie stored by us is present and returns false if not.
function readCookie(name)
{
  var flag = 0;
   // getting the browser cookie values into an array
  var dcmntCookie = document.cookie.split(';');
  // looping over the array to find our cookie
  for(var i=0;i < dcmntCookie.length;i++)
  {
    var ck = dcmntCookie[i];
    // loop for removing extra spaces from the beginning of each cookie
    while (ck.charAt(0)==' ')
    {
       ck = ck.substring(1,ck.length);
    }
    if(ck)
    {
      // splitting the cookie into its name and value
      cparts = ck.split('=');
      // setting the flag if a cookie with the name specified exists
      if (cparts[0]==name)
        flag=1;
     }
  }
  // returning true if cookie exists else returning false
  if(flag) return true;
  else return false;
}
Now as we have created both the createCookie() and readCookie() function, we have to use them for serving our purpose, that is, to hide/display a div element. This is achieved using the checkCookie() function. It checks for the cookie with a given name specified. If the cookie exists then it hides the div. Else if the cookie is not present, a new cookie is created and added to the browser.
function checkCookie(name)
{
  If(readCookie(name))
  {
     // hide the div element using css style attribute
     document.getElementById('myDiv').style.display="none";
     document.getElementById('myDiv').style.visibility = “hidden”;
  }
  // create a new cookie if cookie already not present
  else  createCookie(name,"cookie 4 the day",1);
}
This sums up the article. Hope this helps.
This post is open for your queries and suggestions.
You can download the entire code(with HTML) from here.

Passing only non-Empty fields on form submit

0 comments

Sometimes you have a lot of text-fields and want only those fields to be sent to the server as parameters, which are not left blank (that is which are filled). This helps in decreasing the amount of data being sent to the server.

This is one way of how the above can be done. Lets first start with the basic HTML. The form (say testform) may consists of a number of text fields and a submit button. When the button named “Submit” is clicked, the javascript function “submitFunc()” is called.
<form name="testform">
<input type="text" name="text1" id="text1"><br />
<input type="text" name="text2" id="text2"><br />
<input type="text" name="text3" id="text3"><br />
<input type="button" onclick="submitFunc();" value="Submit">
<form>
Now about the “submitFunc()” function. This function checks each text field by calling the “loopRemove ()” function.
function submitFunc()
{
loopRemove("text",3);

document.testform.action = "http://scriptden.blogspot.com";
document.testform.submit();
}
The “loopRemove()” function loops over the fields, who have a similar name with two parts, one a string (say, ‘text’), suffixed by an integer part in increasing order starting with one (eg. ‘txtField1’,’txtField2’,…).It checks whether the given element’s field value is empty, and if found empty it removes the corresponding element by accessing the element’s parent node.
function loopRemove(startName,count)
{
for(var i=1;i<=count;i++) { if(document.getElementById(startName+i).value=="") { var t = document.getElementById(startName+i); t.parentNode.removeChild(t); } } }
The action path of the form is specified dynamically and the form is submit using the “form.submit()” function. The form thus submitted (with empty elements removed) will pass only the filled field’s values to the page/location specified in the action path.
document.testform.action = "http://scriptden.blogspot.com";
document.testform.submit();
This sums up the article. Hope this helps.
This post is open for your queries and suggestions.

You can download the entire script here.

Script Den has arrived !!

0 comments

Hi Everyone,

I am more than glad to inform you the release of scriptDen , my unofficial blog dedicated for scripting - javascript and actionscript. JavaScript is one of the most important technologies on the web. It provides the means to add dynamic functionality to your web pages and serves as the backbone of Ajax-style web development. Also with Actionscript you can develop nicelooking games and professional websites.

At scriptDen you can find a number of javascript and actionscript code snippets , that could be used and included directly into your own programs. Stay tuned for more posts in coming days.

Welcome to scriptDen.