Archive for September, 2009

References for Multiple Windows

This example demonstrates how subwindows can communicate with objects, functions and variables in the window or frame that creates the subwindow.

Every window object has a property called opener, this property contains a reference to the window or frame that held the script whose window.open( ) statement generated the subwindow, for the main window or frame this value is null.

Code:

Main Window

<html>
 <head>
 <title>Main Window</title>
 <script type="text/javascript">
 function newWindow()
 {
   window.open("subwindow.html", "subwindow", "width=300,height=300");
 }
 </script>
 </head>
 <body>
 <form>
 <input type="button" value="New Window" onclick="newWindow()" />
 <br />
 Text from subwindow:
 <input type="text" name="txt" />
 </form>
 </body>
</html>

Subwindow

<html>
 <head>
 <title>Subwindow</title>
 </head>
 <body>
 <form onsubmit="return false">
 <input type="text" name="txt2" />
 <input type="submit" onclick="opener.document.forms[0].txt.value = document.forms[0].txt2.value" />
 </form>
 </body>
</html>

Note: the parent-child terminology doesn’t apply to subwindows.


Date Object Calculations

Performing calculations with dates frequently requires working with the millisecond values of the Date objects, this is the surest way to compare date values.

Code:

<html>
 <head>
 <title>Date Calculations</title>
 <script type="text/javascript">
 function nWeek()
 {
   var todayMillisec = today.getTime();
   var nWeekMillisec = todayMillisec + (60*60*24*7*1000);
   var dayNextWeek = new Date(nWeekMillisec);
   return dayNextWeek;
 }
 </script>
 </head>
 <body>
 Today is:
 <script type="text/javascript">
 var today = new Date();
 document.write(today);
 </script>
 <br />
 Next week will be:
 <script type="text/javascript">
 document.write(nWeek());
 </script>
 </body>
</html>

In this example you could eliminate the function entirely and let the following two statements in the second body script obtain the desired result:

today.setDate(today.getDate() + 7);

document.write(today);


Breadcrumbs

Breadcrumbs is a navigation aid used in user interfaces. It gives users a way to keep track of their location within programs or documents. A breadcrumb trail allows a user to navigate back up the heirarchy where he would find more revelant information.

Code:

<?php
 $id = $_GET['id'];
 if(strlen($id) < 1)
 $id = "profile";
 $pages = array(
                 'profile' => array(
                                    'id' => 'profile',
                                    'previous' => '',
                                    'title' => 'Profile',
                                    'url' => 'mypage.php?id=profile'
                                   ),
                 'bookmarks' => array(
                                      'id' => 'bookmarks',
                                      'previous' => 'profile',
                                      'title' => 'Bookmarks',
                                      'url' => 'mypage.php?id=bookmarks'
                                     ),
                 'comments' => array(
                                     'id' => 'comments',
                                     'previous' => 'comments',
                                     'title' => 'Comments',
                                     'url' => 'mypage.php?id=comments'
                                    )
              );
 //------------------------------------------------------------------------
 function breadcrumbs($id, $pages)
 {
   $n = array();
   while(strlen($id) > 0)
   {
     $n[] = $id;
     $id = $pages[$id]['previous'];
   }
   for($i=count($n)-1; $i>=0; $i--)
   {
     $page = $pages[$n[$i]];
     if($i > 0)
     {
       print "<a href=\"{$page['url']}\">";
     }
     print $page['title'];
     if($i > 0)
     {
       print "</a> | ";
     }
   }
 }
 ?>
 <html>
 <head>
 <title><?php print $id; ?></title>
 </head>
 <body>
 Location: <?php breadcrumbs($id, $pages); ?><br />
 Page: <?php print $id; ?>
 </body>
 </html>

Save this code as mypage.php in your php server.


Vote System version 1.0.0

Vote system 1.0.0 is a bar graph system giving percentage values, it produces bar columns for each vote option (see photos).

Language: PHP

The system creates a unique hash key for each different url this means that the url is the identifier.

Example:

http://www.mysite.com/movies.php?movie=themovie vote for the movie

http://www.mysite.com/movies.php?movie=themovie&actor=theactor vote for the actor

Features:

  • Add or remove vote options
  • Change options names
  • Change bar colors
  • Change the background color
  • Change text color

Also a manage system is included in this version.

Photos:



Download Vote System version 1.0.0


Date Object

Date is a global object ready to be called upon at any time, the Date is  a static object. When you wish to work with a date, you must to invoke the  Date object constructor function to obtain an instance of a Date object. The value of a Date object is the time in milliseconds from zero o’clock on 1/1/ 1970. You can also grab a snapshot of the Date object for a particular date and time in the past or future by specifying that information as parameters to the Date object constructor function:

var dateObj = new Date(”Month dd, yyyy”);

Date object methods

var dateObj = new Date( );

  • method dateObj.getTime( )
  • value 0-…
  • description milliseconds since 1-1-1970 GTM

———————————————

  • method dateObj.getYear( )
  • value 70-…
  • description minus 1900;four-digit year for 2000+

———————————————

  • method dateObj.getFullYear( )
  • value 1970-…
  • description four-digit year

———————————————

  • method dateObj.getMonth( )
  • value 0-11
  • description month within the year

———————————————

  • method dateObj.getDate( )
  • value 1-31
  • description date within the month

———————————————

  • method dateObj.getDay( )
  • value 0-6
  • decsription day of week

———————————————

  • method dateObj.getHours( )
  • value 0-23
  • description hour of the day (24 hour time)

———————————————

  • method dateObj.getMinutes( )
  • value 0-59
  • description minute of the hour

———————————————

  • method dateObj.getSeconds( )
  • value 0-59
  • description second within a minute

———————————————

  • method dateObj.setTime( )
  • value 0-…
  • decsription milliseconds since 1-1-1970 GTM

———————————————

  • method dateObj.setYear( )
  • value 70-…
  • description minus 1900;four digit year for 2000+

———————————————

  • method dateObj.setMonth( )
  • value 0-11
  • description month within a year

———————————————

  • method dateObj.setDate( )
  • value 1-31
  • description date within the month

———————————————

  • method dateObj.setDay( )
  • value 0-6
  • description day of week

———————————————

  • method dateObj.setHours( )
  • value 0-23
  • description hour of the day (24 hour time)

———————————————

  • method dateObj.setMinutes( )
  • value 0-59
  • description minute of the hour

———————————————

  • method dateObj.setSeconds( )
  • value 0-59
  • description second within the minute

———————————————

Note: the getMonth( ) and setMonth( ) method values are zero based; January is 0, December is 11.


Passing Form Data and Elements to Functions

Javascript features a keyword this that always refers to object contains the script in which the keyword is used.

<input type=”text” name=”textfield” onchange=”myfunction(this)” /> the keyword this pass a reference of the text object to the function.

<input type=”button” value=”click” onclick=”myfunction(this.form)” /> a reference to the entire form, rather than just the object calling the function.

Code:

<html>
 <head>
 <title>Beatle picker</title>
 <script type="text/javascript">
//---------------------------------------------------------------------
 function myfunction_A(form)
 {
   for(var i=0; i<form.Beatles.length; i++)
   {
     if(form.Beatles[i].checked)
     break;
   }
   var beatle = form.Beatles[i].value;
   var song = form.song.value;
   alert(song + " " + beatle);
 }
//--------------------------------------------------------------------
 function myfunction_B(entry)
 {
   var song = entry.value;
   alert(song);
 }
//--------------------------------------------------------------------
 </script>
 </head>
 <body>
 <p>
 <form onsubmit="return false">
 <input type="radio" name="Beatles" value="John Lennon" checked />John
 <input type="radio" name="Beatles" value="Paul McCartney" />Paul
 <input type="radio" name="Beatles" value="George Harrison" />George
 <input type="radio" name="Beatles" value="Ringo Star" />Ringo
 </p>
<p>
 <input type="text" name="song" value="Eleanor Rigby" onchange="myfunction_B(this)"/>
 <input type="submit" name="process" value="Process" onclick="myfunction_A(this.form)" />
 </p>
 </form>
 </body>
 </html>

Submitting and Prevalidating Forms

Before a form is submitted we perform a validation of data in the form. We can do this in a function invoked by the form’s onsubmit event handler.

Code:

<html>
 <head>
 <title>Prevalidating Data</title>
 <script type="text/javascript">
//----------------------------------------------------
 function check(form)
 {
   for(var i=0; i<form.elements.length; i++)
   {
     if(form.elements[i].value == "")
     {
       alert("Field:" + form.elements[i].name + " empty");
       return false;
     }
   }
   return true;
 }
//--------------------------------------------------
 </script>
 </head>
 <body>
 <form onsubmit="return check(this)">
 First name: <input type="text" name="firstName" /><br />
 Last name: <input type="text" name="lastName" /><br />
 <input type="submit" value="Submit" />
 </form>
 </body>
 </html>

Useful linux commands for webmasters

Some basic linux commands are more than necessary to perform and control critical points of your system.

  • Checking the number of  apache processes for example.

ps aux|grep httpd -c

  • Number of ip’s that are connected to your http server.

netstat -plan|grep :80|awk {’print $5′}|cut -d: -f 1|sort|uniq -c|sort -nk 1

  • Hits of googlebot at your log files.

grep googlebot /var/log/httpd/YOUR_access_log* | awk ‘{print $7}’|cut -d: -f 1|sort | uniq -c|awk ‘END{print NR}’

or better at he specifice date.

grep googlebot /var/log/httpd/YOUR_access_log* |grep day?/month?/year? |awk ‘{print $7}’|cut -d: -f 1|sort | uniq -c|awk ‘END{print NR}’

  • This command is reading disk swapping under the swap column.

vmstat 1 10

  • Mysql resources..

ps aux | awk ‘{print $1 ” CPU ” $3 ” MEMORY ” $4}’|grep mysql


Ajax XMLHttpRequest

The function below creates a XMLHttpRequest object; sends the request to the server and finaly receives the data.

Variables:

target: the ID of the HTML element where the rensponse message is displayed.

method: POST or GET.

url: server side script that receives the request.

param: the data.

slideIt: (milliseconds) determines the duration of the rensponse message occurence.

loadImage: If is not zero (0) load an image during the request proccess; its value is the ID of the HTML element where the image appears.

shoWait: displays a message during the request proccess; if its value is zero (0) nothing happens else the value is the message.

Code:

function Ajaxify(target, method, url, param, slideIt, loadImage, shoWait)
{
  if(shoWait != 0)
  {
    document.getElementById(target).innerHTML = shoWait;
  }
  if(loadImage != 0)
  {
    document.getElementById(loadImage).innerHTML = '<img src="my_image.gif"/>';
  }
 //Find Correct XMLHTTP Connection
 if(!window.XMLHttpRequest)
 {
   window.XMLHttpRequest = function()
   {
     var types = [
    'Microsoft.XMLHTTP',
    'MSXML2.XMLHTTP.5.0',
    'MSXML2.XMLHTTP.4.0',
    'MSXML2.XMLHTTP.3.0',
    'MSXML2.XMLHTTP'
    ];
    for(var i = 0; i < types.length; i++)
    {
      try
      {
        return new ActiveXObject(types[i]);
      }
      catch(e)
      {}
    }
    return false;
   };
 }
 //Create Socket
 NewRequest = new XMLHttpRequest();
 NewRequest.open(method, url, true);
 NewRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 NewRequest.send(param);
 NewRequest.onreadystatechange = function()
 {
   if (NewRequest.readyState == 4)
   {
     if (NewRequest.status == 200)
     {
       if(loadImage != 0)
       {
         document.getElementById(loadImage).innerHTML = '';
       }
       if(slideIt != 0)
       {
         var comment = new Fx.Slide(target, {duration: slideIt}).hide();
       }
       document.getElementById(target).innerHTML = unescape(NewRequest.responseText);
       if(slideIt != 0)
       {
         comment.toggle();
       }
     }
     else
     {
       document.getElementById(target).innerHTML = 'Ajax Error';
     }
   }
 };
 }

The Select Object

The most complex form control to script is the select element object, this object contains an array of options objects.Some properties belong to the entire select object; others belong to individual options inside the select object.The most important property of the select object is the selected property document.myform.selectName.selectedIndex.

Other properties of an option object are text and value:

document.myform.selectName.options[i].text

document.myform.selectName.options[i].value

Code:

<html>
 <head>
 <title>Select Object</title>
 <script type="text/javascript">
//----------------------------------------------------
 function myfunction()
 {
   var selectList = document.forms[0].myselect;
   alert("Selected text:" + selectList.options[selectList.selectedIndex].text + "\n" +
   "Selected value:" + selectList.options[selectList.selectedIndex].value);
 }
//---------------------------------------------------
 </script>
 </head>
 <body>
 <form>
 <select name="myselect" onchange="myfunction();">
 <option value="1">Home</option>
 <option value="2">Browse</option>
 <option value="3">Search</option>
 </select>
 </form>
 </body>
</html>