Thursday, December 20, 2012

PHP Include and Include_once

What will be the output of following PHP code snippet?

<?php
$i=0;
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";

?>

Content of "inc.php" is given below..


<?php
$i++;
echo "Included :: $i";
?>


Answer ::
---------------
Included :: 1
1
Included :: 2
2
2
Included :: 3
3

Discussion ::
-------------
The first "include_once()" includes the file once which increments the value of $i to 1. Hence the first output is shown from first inclusion of inc.php.

Next "include()" statement again includes the inc.php which increments the $i to 2 and the output follows.

Next "include_once()"  does not include the "inc.php" as it was previously included... Hence the old value of $i [2] is retained.

The last "include" again includes the "inc.php" and hence increments the $i again to make it to 3.

AGain check the output of the following code snippet

<?php

$i=0;
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
?>


The output ::
---------------
Included :: 1
1
1

Discussion ::
---------------
The first "include()" includes the file "inc.php" which increments the value of $i to 1 and prints the  first line as shown in the output above.
Next "include_once()" does not include the file again ... hence the last value of $i (1) is retained.

Friday, December 14, 2012

How to create stylish SelectBox with HTML and Javascript

We can create good-looking selectbox in various ways ... one of them is described below.

1. We'll use a DIVwith a background image which will represent the finally good looking selectBox
2. We'll put a SelectBox inside the DIV and make the SelectBox completely invisible by setting its opacity to zero and Z-index to 100
3. We'll have a SPAN [Sibling to SelectBox] inside the DIV, which will show the final text after we select an Item from the SelectBox

Process ::

1. We are shown the SPAN with a default text
2. When we click on the DIV, the SelectBox receives the click because of having the highest z-index
3. One JS function runs when click event is captured on the SelectBox and that function extracts the textContent from the SelectBox and puts it in the SPAN


 -----OUTER DIV ----------------------------------------
|  -- SelectBox [Invisible but stays at the top] -----  |
| |                                                   | |                            
| |___________________________________________________| |
|                                                       |
|  -- SPAN [Holds the text] --------------------------  |
| |                                                   | |                            
| |___________________________________________________| |
|                                                       |
|-------------------------------------------------------|


Check the code below and see the effect

<script type='text/javascript'>
  function run(elem)
  {
    var p = elem.nextElementSibling;
    if( elem.value!='')
     p.innerHTML = elem.options[elem.selectedIndex].textContent;
    else
     p.innerHTML = "Select Order";   
  }
 </script>

<div>
  <!-- OUTER DIV STARTS -->
  <div class="select1" style='height:25px;display:block; background: url("bg_select.png") no-repeat scroll 1px 2px transparent;'>
        <!-- SELECTBOX Starts -->
    <select title="Select Order" class="select2" id="select" onchange="run(this)" name="data[productsortoforder]" style="z-index: 10; opacity: 0;">
        <option value="">Select Order</option>
        <option value="name-asc">Name: Ascending</option>
        <option value="name-desc">Name: Descending</option>
        <option value="price-lowtohigh">Price: Low To High</option>
        <option value="price-hightolow">Price: High To Low</option>
    </select>
        <!-- SPAN STARTS -->
    <span style='border:0px solid red; margin-left:-137px;margin-top:3px; position:absolute; font-family:helvetica; font-size:12px'>Select Order</span>      
  </div>
</div>


Check the final getUp as displayed below ::



Save the picture below as bg_select.png and run the above code to check the effect.


Friday, November 23, 2012

Basic Regular Expression Patterns I

Here, I'll discuss on the usage of Regular Expressions in various validation checking. We are using Javascript Regular expression patterns. These patterns can be tested on any input end-user provides.

Example 1. Input NUMBER

Conditions :
1. The input number must be 8 digit long
2. It should start with '5', '6' or '9'

Code :
var pattern = /^[569]{1,1}[0-9]{7,7}$/  
var tel_no  = "56895869";  // User Input
pattern.test(tel_no);      // Will return true as Pattern is matching

Example 2. Input STRING

Conditions :
1. The input string should start with the letter 'T' in capital
2. The second letter is a vowel
3. Second letter is small case letter
4. The third letter is any small letter non-digit character
5. The whole string is a 3-letter word.


Code :
var pattern = /^T[aeiou][a-z]$/;

Example 3. Input STRING

Conditions :
1. The string should start with any non-digit character including underscore
2. The string can have only underscore as special character.
3. The string can have maximum 10 characters.

Code : 

var pattern = /^[^0-9_][0-9a-zA-Z_]{0,9}$/;

Example 4. Input STRING

Conditions :
1. The input string must have the word "Band"


Code :
var pattern = /\bBand\b/;

Discussions :: The '\b' modifier is used to find word boundaries. That means string like

"Band, great!!!"
"Test Band..."
"This is my Band. Great na?",
"Nice Band!!!"
"OK!!Band starts now"
"Good Band"

will test true against the pattern. This pattern matches for "Band" followed by a newline character, "Band" word followed by punctuation mark or any such mark followed by the word "Band" etc.

Strings like 

"Great Bands"
"Bands of Britain"

will always return false because "Band" has not appeared as a single word. Check next part of this article here.

Tuesday, November 06, 2012

MYSQL :: Concatenation of columns in multiple rows

Suppose, we have a table as shown below ::

ID Animal_name
1 Lion
2 Tiger
3 Monkey
4 Horse
The "animal_table" table

Suppose, the table has a name "animal_table". Now, I want to have all the values in the "Animal_name" column to be merged into a single string. We can do it in MySQL itself with the help of "GROUP_CONCAT" function as shonw below.

SELECT group_concat( `Animal_name` SEPARATOR ', ' ) FROM `animal_table` 

The output is shown below :
Lion, Tiger, Monkey, Horse

The phrase "SEPARATOR ', '" actually defines the glue string which merges the values together.

If we want the whole table sorted before the concatenation, we would write the query as follows.

SELECT group_concat( DISTINCT `Animal_name` ORDER BY `Animal_name` SEPARATOR ', ' ) FROM `animal_table`

"DISTINCT" has to be used with "ORDER BY" clause.

Monday, November 05, 2012

Output buffering in PHP


I have a very small yet so interesting code sample on buffering in PHP.

Suppose, I have my web-page divided in two segments.. 

1. Main PHP [main.php] for all logic.
2. Template PHP file [template.php], which I include at the bottom of main.php.

Main.php
----------
<?php
include("template.php");
?>

template.php
----------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
This is a test template. This test template works well. I want to learn more about PHP templates. This test template is finally working perfectly.
</body>
</html>


Problem :: How to change all occurrences of the word "test template" to "template" without modifying the template file itself?

Solution :: We can manipulate the buffer features that comes with PHP and by doing that we can make required changes to the output PHP script generates before rendering onto browser. 

We need to change the main.php as shown below.

<?php
function show($buffer)
{
  return str_replace("test template","template",$buffer);
}

// Start The Buffer with show() function 
// as a callback ob_start("show"); 
include("template.php");

// Send the Buffer content to Browser
ob_end_flush();
?>

The line "ob_start('show')" line tells PHP server to start buffering the server output and apply the show() function as CallBack on the output. That means, all occurrences of the phrase "test template" are changed to "template" before they are finally sent to browser. And lastly, ob_end_flush() function renders the output to the browser. So, the output of the above script is shown below.

This is a template. This template works well. I want to learn more about PHP templates. This template is finally working perfectly.

Image data handling in PHP


If you are recieving any Image data from any iPhone or other mobile devices, your image data may come in another hex coded format as displayed below. Here I am showing the methods for ::

1. Creating such hex coded image data from an image file in hard disk
2. Retrieving/recovering back the original image file from that hex coded data.

1. To create such hex coded data, use the following code

<?php
// READ the image file content and then 
// strtohex() the data
echo strtohex( file_get_contents( "small.jpg" ) );


function strtohex($dec)

{
$str = '';
for ($i=0; $i < strlen($dec); $i++)
{
$k = "";
 
// Space after every 4 HEX numbers
  if( $i>0 && $i %4 == 0 ) $k = " ";
 
// GET ASCII
  $v = dechex( ord( $dec[$i] ));
  
  // Prefix a '0' if the HEX number is 1 digit long
  if(strlen($v) == 1 ) $v = "0".$v;

  $str .= $k . $v;

}
return $str;
}
?>

The above code had generated the following output with the image I input :

ffd8ffe0 00104a46 49460001 01010060 00600000 ffdb0043 00020101 02010102 02020202 02020203 05030303 03030604 
04030507 06070707 06070708 090b0908 080a0807 070a0d0a 0a0b0c0c 0c0c0709 0e0f0d0c 0e0b0c0c 0cffdb00 43010202 
02030303 06030306 0c080708 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 
0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0cffc0 00110800 0f001603 01220002 11010311 01ffc400 1f000001 05010101 01010100 
00000000 00000001 02030405 06070809 0a0bffc4 00b51000 02010303 02040305 05040400 00017d01 02030004 11051221 
31410613 51610722 71143281 91a10823 42b1c115 52d1f024 33627282 090a1617 18191a25 26272829 2a343536 3738393a 
43444546 4748494a 53545556 5758595a 63646566 6768696a 73747576 7778797a 83848586 8788898a 92939495 96979899 
9aa2a3a4 a5a6a7a8 a9aab2b3 b4b5b6b7 b8b9bac2 c3c4c5c6 c7c8c9ca d2d3d4d5 d6d7d8d9 dae1e2e3 e4e5e6e7 e8e9eaf1 
f2f3f4f5 f6f7f8f9 faffc400 1f010003 01010101 01010101 01000000 00000001 02030405 06070809 0a0bffc4 00b51100 
02010204 04030407 05040400 01027700 01020311 04052131 06124151 07617113 22328108 144291a1 b1c10923 3352f015 
6272d10a 162434e1 25f11718 191a2627 28292a35 36373839 3a434445 46474849 4a535455 56575859 5a636465 66676869 
6a737475 76777879 7a828384 85868788 898a9293 94959697 98999aa2 a3a4a5a6 a7a8a9aa b2b3b4b5 b6b7b8b9 bac2c3c4 
c5c6c7c8 c9cad2d3 d4d5d6d7 d8d9dae2 e3e4e5e6 e7e8e9ea f2f3f4f5 f6f7f8f9 faffda00 0c030100 02110311 003f00f8 
3bc4dff0 428d2ad7 e0d477da 37c5ed42 ff00e211 fd9d6dbf 6919345b df0725a6 8cba3318 fed16035 14bf9663 7880ca53 
fd084721 440cf16f 253d43c6 3ff06b2f 8abc07f1 b3e2b787 356f881e 20d37c31 e01f15f8 03c31a0f 8a6efc03 34161e35 
ff00849b 50b4b1b9 9ed59aec 47ff0012 e92ec091 23925dec a159a02d c7c9ff00 b70ffc15 b3c7dfb6 07c1af85 7f0e74fd 
43c61e08 f87bf0fb e1ae83e0 1d4fc316 fe2bb9b8 d1bc5171 a5962baa 4d68ab14 22472202 11924286 da3fde36 d5dbf485 
ff00fc1c 85f6dfda 9fe3cfc4 cff8535b 7fe17778 afe1bf89 ff00b37f e12dcff6 2ffc2217 96b73e47 9bf62fdf 7db3ecdb 
77ec8fc9 df9db2e3 0403c3ff 006f8ff8 24e695fb 25fc02f1 27c46f08 7c49d43c 71a2781b e306a9f0 53c4506b 1e174d06 
ea2d66ca dbed1f68 b458af6f 127b3744 986f91e0 914ac7fb a60e4a15 e41fb7c7 edf1e3ef f8281fc7 df1278bf c5fe24f1 
85f6897d e20d5358 f0ef8775 8f115cea f6be11b7 bdb9f3be c569e6e1 238d1161 8ff771c6 18411fca 02800a00 ffd9 

2. Now to get back the original Image file from the above output, check the following code snippet.


<?php

// Take the whole data in a variable
$image_data = "ffd8ffe0 00104a46 49460001 ...."  ; 

// Remove Spaces

$img_data = str_replace(" ","", $image_data);

// Convert From HEX to String

$img_data = hextostr($img_data);

//Create a new file

$fp = fopen("original.jpg" ,"w+");

//Write data to file

fwrite($fp, $img_data);

// Close the file

fclose($fp);

function hextostr($hex)

{
$str = '';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$m = hexdec($hex[$i].$hex[$i+1]);
$str .= chr( $m );
}
return $str;
}
?>

The code above is quite self-explanatory. It takes every 2 bytes of image data, converts them to decimal and then a corresponding ASCII character is generated.

Check article on How to Convert image data to base64 encoded in PHP.

Convert image data to base64 encoded in PHP


Here I want to show, how to convert simple image to base64 encoded data which can be used directly with the HTML <img> tag.

Step 1 : Create/Get an image which you need to convert into base64-encoded data.
Step 2 : Write the following PHP code to effect the conversion.

<?php
echo $str =  base64_encode(file_get_contents("test.jpg"));
?>

Step 3 : Base64 encoded data will be echoed on the page. We can use this base64 encoded code in HTML img tag directly as shown below.

<img
src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAALCAAQAGkBAREA/8QAGwAAAgIDAQAA
AAAAAAAAAAAABgcFCAIDBAr/xAAqEAABBQEAAgICAQIHAAAAAAAEAQIDBQYHCBQREgATFhUhJDJi
gZGi0f/aAAgBAQAAPwDxFeL+NzPQu54fJa+sS4z1sTZMsK2Qo8NpTR6g8uFqlVc4x8SftihVfWna
75RUX5aqtdcPYcS5re8v6ddL48aXx/s8M2mNo9DdaXWWYOoQq0QAiqhD1IosTY5WzM+FDSYn3CAP
kodiOEte7WeD9iX2PGm4jm8K8Zmfi5dJGuvgj/cJK2vm0zmss9I/RqqteU1VAc1zUT7A/X4Y5ZMX
hPI6Ot7BaB+P1j1svM9ksMhQ5ik0m5DMr86wH2mujnpyLGWaACaOONSbEcouVTGrIY9WJ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a3lG
kCkCH+wbX15Dpi/ZnKeQO6KIdYfNeRHNq/d9ODM5hHWcW62PXVd7kc8YsVhSjVErJK68p3zSRBPt
A52yWTa5/rVUhcyR/ceGJFfu03ZOHYbnuhwPAM5tEn6EQB/MtZ0AmqW1FqKk6A4KkpQ6FyhpCVPC
95hM36Zvo+YR7C2qIRXtzW968S9Xs6vqdrR9gtNrnQqGStpXNyNXlrCyzYMEQAx00RtncjglFiwq
YTDOWREx8sjBZ/lgzV9W+VufPpLJ+orLdl/b+QNL1kllcKCTUwZ8GN/s14shR8JEtjC97oxRSRkC
IGZEhZzXIjULef8AmNlcr3Xo+utavQWXMtrdT6KsBQWvfoKG+iELFCtxAZrRQIZyQz7GntWwWiRl
ClxPf7fpxC/gDiu+cqucyFgeyUWyWnyOlttRzvZYIupF11ARaHsNnqP1WCRioCWUr7VbBpJBoZ0E
DBhpI3RziQHk35CZ3q1ViMXkoNibQ4eS6nj1vRLplvr9KReJXTzus44GywheiQNMIOkVgX7YjRZH
+m6J0Dadf7r/AMP/APfz/9k=" alt="Test Image"/>

Check out the output as shown below.







Problem :: How to create an Image from this base64? This is very simple.

<?php
// Image Data
$image_data = 
"/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAALCAAQAGkBAREA/8QAGwAAAgIDAQAA
AAAAAAAAAAAABgcFCAIDBAr/xAAqEAABBQEAAgICAQIHAAAAAAAEAQIDBQYHCBQREgATFhUhJDJi
gZGi0f/aAAgBAQAAPwDxFeL+NzPQu54fJa+sS4z1sTZMsK2Qo8NpTR6g8uFqlVc4x8SftihVfWna
75RUX5aqtdcPYcS5re8v6ddL48aXx/s8M2mNo9DdaXWWYOoQq0QAiqhD1IosTY5WzM+FDSYn3CAP
kodiOEte7WeD9iX2PGm4jm8K8Zmfi5dJGuvgj/cJK2vm0zmss9I/R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XZqwuLtbU4ixPJWCKMaL2CS
5yJn+vDDFAz9039oIoGojWo1Py5ND2jx+6BjcHUd/wAxvF0XNKoXO09thCqRw2jzwkz5QwL0a3lG
kCkCH+wbX15Dpi/ZnKeQO6KIdYfNeRHNq/d9ODM5hHWcW62PXVd7kc8YsVhSjVErJK68p3zSRBPt
A52yWTa5/rVUhcyR/ceGJFfu03ZOHYbnuhwPAM5tEn6EQB/MtZ0AmqW1FqKk6A4KkpQ6FyhpCVPC
95hM36Zvo+YR7C2qIRXtzW968S9Xs6vqdrR9gtNrnQqGStpXNyNXlrCyzYMEQAx00RtncjglFiwq
YTDOWREx8sjBZ/lgzV9W+VufPpLJ+orLdl/b+QNL1kllcKCTUwZ8GN/s14shR8JEtjC97oxRSRkC
IGZEhZzXIjULef8AmNlcr3Xo+utavQWXMtrdT6KsBQWvfoKG+iELFCtxAZrRQIZyQz7GntWwWiRl
ClxPf7fpxC/gDiu+cqucyFgeyUWyWnyOlttRzvZYIupF11ARaHsNnqP1WCRioCWUr7VbBpJBoZ0E
DBhpI3RziQHk35CZ3q1ViMXkoNibQ4eS6nj1vRLplvr9KReJXTzus44GywheiQNMIOkVgX7YjRZH
+m6J0Dadf7r/AMP/APfz/9k=";

// Create Image File
$fp = fopen("new.jpg", "w+");

//Write the new Data
fwrite($fp, base64_decode($img_data));

// Close the file
fclose($fp);

?>

Wednesday, October 31, 2012

Javascript Event Bubbling 2

I have already discussed the issues related to Event Bubbling behaviour in various browsers in article "Javascript Event Bubbling". I just have another small example of such event bubbles shown below.


HTML
-------  

<div>
   <a href="javascript:alert('ANCHOR clicked')">
     <span style='font-weight:bold' onclick="alert('SPAN clicked');">SPAN</span> Anchor
   </a>
</div>

The output of above HTML is shown below.















The text "Anchor" is appearing inside the Anchor tag . When it is clicked , "ANCHOR clicked" message is shown. But when an child element of this anchor, a span element with text "SPAN" is clicked, the message "SPAN clicked" message is shown as span element's click event is fired. Next, span element's parent is an Anchor tag which has "click" event defined also. Due to Event Bubbling effect, "click" event of the Anchor tag is also fired and as a result, both the messages "SPAN clicked" and "ANCHOR clicked" are alerted on screen one by one. If the anchor tag had a parent element with its own click event, that would have also been fired in the same process. 

To prevent this, we can make a small change in the above HTML as shown below.

<div>
   <a href="javascript:alert('ANCHOR clicked')">
     <span style='font-weight:bold' onclick="alert('SPAN clicked'); return false;">SPAN</span> Anchor
   </a>
</div>

We have appended a "return false;" statement to the "onclick" property of the Span element. And by doing this, the control does not pass form child's triggered event to parent's similar event. The above solution ran perfectly on Chrome, Firefox and IE 6,7,8,9.

Javascript Event Bubbling


I have a Div element with a small Span element inside it, on my webpage. I have attached two alerts against the click event of each elements. The code snippet and screen-shot is given below.

HTML
-------
<div onclick="javascript:alert('Outer DIV Clicked')">
     <span onclick="javascript:alert('Inner Span Clicked')">?</span>
</div>

Problem :: 
When we click on anywhere within the Div element, the message "Outer DIV Clicked" is shown, but when we click on the inner question mark icon [inside the Span element], "click" events of both the elements [Span and Div] are sequentially fired and as a result the following messages are shown on screen one by one.

Inner Span Clicked
Outer DIV Clicked















At first, the click event of Span is fired, then same event of outer Div is fired. This type of incident is called event bubbling. We can stop this kind of behaviour in the following way.

Solution :: 
We need to re-write the Span element as the following way

<span onclick="span_click(event)">?</span>

and we need to write the "span_click" function as shown below.

<script>
function span_click(e)
{
  if (!e) var e = window.event;
  e.cancelBubble = true;   // for IE
  if (e.stopPropagation) 
    e.stopPropagation();   // for Firefox 
  alert('Inner Span Clicked');
}
</script>

By manipulating the "cancelBubble" property available with IE browser and calling stopPropagation() method in Firefox browser, we can stop this event bubbling. Just check this out.

Find more on Event Bubbling in next article "Javascript Event Bubbling 2"

Javascript FadeOut


Situation :: I have two small question mark icons on my page and when clicked, each of those icons shows related tooltip help text in a DIV and that DIV fades away in some seconds. The scenario can be better understood from the picture below.


As stated, when the 1st icon is clicked, the corresponding tooltip text is displayed and the other tooltip text is immediately hidden.











If we use fadeout() function of jQuery, we need to write the HTML and JS as shown below.

HTML 
-------
<!-- Creating the two question mark icons as displayed in the picture. -->
<span onclick = 'display_help(1); return false;'>?</span>
<span onclick = 'display_help(2); return false;'>?</span>

<!-- ToolTips, Iniatially made hidden -->
<div id='consumer_tips' style="background-color:#FFA130;width:130px;font-size:12px;color:#1658A2;display:none;padding:5px">As a Consumer, you can accept various offers from Merchants.</div>

<div id='merchant_tips' style="background-color:#FFA130;width:130px;font-size:12px;color:#1658A2;display:none;padding:5px">As a Merchant, you can offer various goodies to Consumers.</div>


JavaScript
-------------
function display_help(type)
{
  // Show FIRST TIP and FadeOUT 
  if( type == 1 )       
  { j("#merchant_tips").hide();
    j("#consumer_tips").show().fadeOut(15000);
  }

  // Show SECOND TIP and FadeOUT
  if( type == 2 )      
  { j("#consumer_tips").hide(); 
    j("#merchant_tips").show().fadeOut(15000); 
  }
}


Testing Scenario:: We have the following scenario.

1. We click on the 1st icon, 1st tooltip is shown and it starts to fade out. 2nd tooltip is made hidden.

2. We click on the 2nd icon, 1st tooltip is made hidden, the 2nd tooltip is shown and it starts to fade out.

3. We click on the 1st icon again, 2nd tooltip is hidden. 1st tooltip is shown again.

Problem ::  
If we repeat the above stated processes quickly, we'll see that the third process [stated in point 3 above] is showing first DIV in faded condition. This happens due to the timer which started the fading in first process [stated in point 1]. This timer is still in function because it has not timed-out yet as we had gone through the clicks very fast. The picture below is showing the faded effect.















Solution :: We can fix the issue by writing our own Javascript timer function. Our objective will be as follows ::

1. When 1st icon is clicked, we set a flag to 1; we start a timer for fading out; when the opacity of the tooltip DIV reaches below 0 we hide the DIV completely

2. When we click on the 2nd icon, we set another flag to 1 and clear the first flag and first timer; similarly the second DIV is made hidden when its opacity goes below 0;

3. When we again click the 1st icon, the related flag and timer are set whereas the flag and timer for second icon/toolbar are all cleared.

The code is given below .. 

<script type='text/javascript'>
function display_help( type )
{
  // Show Consumer TIPs and FadeOUT
  if( type == 1 ) 
  {   
      // Hide 2nd DIV
      j("#merchant_tips").hide();
      // Show 1st DIV
      j("#consumer_tips").show();
      // Set flag related to 1st icon
      tip1 = 1; op1 = 1.0;  
      // Clear old timer for fading 
      clearTimeout( timer1 );
      // Call the fade_out function 
      fade_out("consumer_tips", 1);  
  }
  // Show Merchant TIPS and fadeOut 
  if( type == 2 )  
  { 
     // Hide 1st DIV
     j("#consumer_tips").hide(); 
     // SHow 2nd DIV
     j("#merchant_tips").show(); 
     // Set flag related to 2nd icon/DIV
     tip2 = 1; op2 = 1.0;
     // Clear old timer for fading
     clearTimeout( timer2 );
     // Call the fade_out function
     fade_out("merchant_tips", 2);  
  }
}

// Fade_Out function, which sets timer for changing the Opacity of a DIV. 
// Lower the opacity, more faded the element looks. 

function fade_out(div_id, mode)
{
  // FOR 1st DIV/Icon  
  if(mode == 1 && tip1 == 0 ) 
  {
    clearTimeout( timer1 );
    return;
  }
  
  // FOR 1st DIV/Icon  
  // Consumer tips is fading Out
  if( mode == 1 && tip1 == 1 ) 
  {
    // Setting the timer
    timer1 = setTimeout( function(){ fade_out(div_id, mode); }, 100 );
    
    // Set the Opacity
    j("#" + div_id).css("opacity", op1);
    
    //Decrease the opacity
    op1 -= .01;
    
    // If opacity goes below 0, clear the timer
    if(op1 < 0 )
    {  
       // Clear the timer
       clearTimeout( timer1 ); 
       tip1 = 0;  
       j("#" + div_id).css("display", "none"); 
    }
  }
  
  // FOR 2nd DIV/Icon  
  if(mode == 2 && tip2 == 0 )
  {
    clearTimeout( timer2 );
    return;
  }
  
  // FOR 2nd DIV/Icon  
  // Merchant tips is fading Out
  if( mode == 2 && tip2 == 1 ) 
  {
    // Setting the timer
    timer2 = setTimeout( function(){ fade_out(div_id, mode); }, 100 );
    
    // Set the opacity
    j("#" + div_id).css("opacity", op2);
    
    // Decrease the opacity
    op2 -= .01;
    
    // If opacity goes below 0, clear the timer
    if(op2 < 0 )
    {  clearTimeout( timer2 ); 
       tip2 = 0;  
       j("#" + div_id).css("display", "none"); 
    }
  }
}    
</script>  

Friday, October 26, 2012

Printing Special Characters in HTML

HTML has alternative coding for showing special characters. 

For example :

"&nbsp;" is equivalent to having a space
"&copy;"  is equivalent to copyright sign

When we write "&copy" in our HTML, browser renders the corresponding copyright sign in the screen.

But problem is, how to print the word "&copy" itself on the screen? 

Here is the solution :
"&amp;copy;

Write the above code and this would do just the thing we want to achieve.

Saturday, October 20, 2012

Email validation in Javascript

We can check whether an given email address is ok or not through the regular expression show below.

<script type='text/javascript'>
// RegExp Pattern
var pattern = /^[a-zA-Z]+[a-zA-Z0-9_]*@[A-Z0-9a-z]+(\.){1,1}[a-zA-Z]{2,3}$/ ;


// Email to check
var email = "a@a.com";

// Show the result
console.log( pattern.test(email) );
</script>

The above code will print 'true' in your browser console. Let's dissect the regular expression to understand it more clearly.

1. ^[a-zA-Z]+     => means, the Input must start with character a through z in small/capital letters
2.[a-zA-Z0-9_]*  => means, characters and digits and underscore may or may not appear next. 
3. @         => '@' character must appear next
4. [A-Z0-9a-z]+  => means, character, digits will appear next, minimum 1 character/digit is must
5. (\.){1,1} => then, there must be a dot (.)... {1,1} means minimum 1 times and maximum 1 times respectively
6. [a-zA-Z]{2,3}$  => means, a series of character,digits will appear at the end of the input, but that series will have minimum 2 and maximum 3 characters/digits

Numeric Data validation in Javascript

To check whether a user-given number is numeric, we can test it with a regular expression pattern. 

Problem :: Suppose, on a webpage, there is a textbox where user needs to input valid numeric data. That data has to be greater than zero also. 

Solution :: We can write a javascript function as given below.

<script type='text/javascript'>
function test_numeric($data)
{
 // Define Regular Expression Pattern 
 var $pattern = /^[0-9]+(\.)?[0-9]+$/;

 // Test the pattern
 $result = $pattern.test( $data );

 // Input data is matching our expected pattern 
 if( $result ) 
 {
   // Now check if Data is Positive
   if( parseFloat( $data ) > 0 )
     return parseFloat( $data );
   else
     return 0;

 }
 // Input data does not match our expected pattern
 else 
 {
    return 0;  
 }
}
</script>

The above function returns the floating representation of input data when the Input data is valid or matches our given pattern. If it does not match the pattern, 0 is returned.

Now let's simplify the regular expression /^[0-9]+(\.)?[0-9]+$/ 
1. ^[0-9]+  => means the Input data should start with digits 0 to 9, 1 or more digits may appear.
2. (\.)?    => means the character dot (.) may or may not appear at all
3.  [0-9]+$  => means the input data ends with digit[0-9] sequence and may have 1 or more digits in it.

Another point, we need to discuss here. The above regular expression will pass "0009" as a valid input. That's why we have returned floating point representation of  the original number by using the statement :: 

return parseFloat( $data );

The above statement would return "9" if the input was "0009".