Monday, December 26, 2011

Javascript to Move a DIV around (touchscreen version, drag-and-drop for iphone/ipad/android)

This is the touchscreen version of the post:

I believe most browser in touchscreen mobile devices will be supported such as iPhone/iPad/Android. Blackberry won't be supported as it is running browser with very low level of compatibility.

Here are the codes:

<script type="text/javascript">
var PositionFlag = 0;
var p1;
var p2;
var p3;
var p4;
var pos_x;
var pos_y;
var diff_x;
var diff_y;
var move_x;
var move_y;
var once = 0;

function is_touch_device() {
try {
return true;
catch (e) {
return false;

var touch_capable = is_touch_device();

function init() {
if (touch_capable) {
document.getElementById('dis_info5').innerText = "Touch Capable";
document.addEventListener('touchmove', function(event) {
}, false);

document.getElementById('myBox').style.cursor = 'hand'; = 'crosshair';

function UpdateXY() {

box_x = document.getElementById('myBox').offsetLeft;
box_y = document.getElementById('myBox').offsetTop;

if (!touch_capable) {

move_x = window.event.clientX;
move_y = window.event.clientY;

p1 = 'Mouse: X=' + move_x + ' Y=' + move_y ;
document.getElementById('dis_info1').innerText = p1;
else {

move_x = event.touches[0].pageX;
move_y = event.touches[0].pageY;

if (move_x > box_x-225 && move_x < box_x+225 && move_y > box_y-225 && move_y < box_y+225) {
PositionFlag = 1;
else {
PositionFlag = 0;

p4 = 'Touch ' + event.touches.length + ': X=' + event.touches[0].pageX + ' Y=' + event.touches[0].pageY ;
document.getElementById('dis_info4').innerText = p4;

p2 = 'myBox: X=' + box_x + ' Y=' + box_y ;
document.getElementById('dis_info2').innerText = p2;

if (once == 0) {
diff_x = move_x - box_x;
diff_y = move_y - box_y;


p3 = 'Diff : X=' + diff_x + ' Y=' + diff_y ;
document.getElementById('dis_info3').innerText = p3;

if (PositionFlag == 1) {
x = move_x - diff_x;
y = move_y - diff_y;

document.getElementById('myBox').style.left = x;
document.getElementById('myBox') = y;
once = 1;



<div id="myBox" style="position:absolute;z-index:100;" onmousedown="PositionFlag=1;" onmouseup="PositionFlag=0;once=0;" width=75 height=75><table border=1 width=75 height=75><tr><td bgcolor=#ddeeff align=center><br>  <font color=orange>orange</font>  <br><br></td></tr></table></div>


if (!touch_capable) {
document.write("<body onmousemove=UpdateXY() onload=init()>");
else {
document.write("<body ontouchmove=UpdateXY() onload=init()>");


<div id="dis_info1"></div>
<div id="dis_info2"></div>
<div id="dis_info3"></div>
<div id="dis_info4"></div>
<div id="dis_info5"></div>


Basically all the tricks are highlighted in green. Instead of using onmousemove as the listener, use ontouchmove. There is also a need to set up an event listener for ontouchmove so that you just don't only get the first touch coordinates. In order to get all the coordinates, the event listener has to be set up as shown in green above.

Those +225 and -225 shown in red is a matter of preference. You can change it to other values. I find these numbers OK as they are buffers in case your finger moves too fast. If you choose number that is too big, the drag can be smooth but the area affected will be large.

Lastly, the broswer sniffer. I used to use the iphone/ipad/Android sniffer but it is getting nowhere as new mobile devices are being released from time to time and there is a need to maintain the sniffer to add in new supported device. I use the touch capability sniffer which is maintenance free and more compatible.

Hope you like this special javascript trick for mobile devices using touchscreen!!!
Read More »

Javascript to Move a DIV around (non-touchscreen version)

Ever wonder how to use javascript to move a DIV around your web page? This fascinated me because it is so cool to make your web page to have the drag-and-drop feature.

The trick is to use the onmousemove event listener on the body level. Here are the codes:

<script type="text/javascript">
var PositionFlag = 0;
var p1;
var p2;
var p3;
var p4;
var pos_x;
var pos_y;
var diff_x;
var diff_y;
var mouse_x;
var mouse_y;
var once = 0;

function UpdateXY()
mouse_x = window.event.clientX;
mouse_y = window.event.clientY;
p1 = 'Mouse: X=' + mouse_x + ' Y=' + mouse_y ;
document.getElementById('coorinfo1').innerText = p1;

box_x = document.getElementById('myBox').offsetLeft;
box_y = document.getElementById('myBox').offsetTop;

p2 = 'myBox: X=' + box_x + ' Y=' + box_y ;
document.getElementById('coorinfo2').innerText = p2;

if (once == 0) {
diff_x = mouse_x - box_x;
diff_y = mouse_y - box_y;


p3 = 'Diff : X=' + diff_x + ' Y=' + diff_y ;
document.getElementById('coorinfo3').innerText = p3;

if (PositionFlag == 1) {
x = mouse_x - diff_x;
y = mouse_y - diff_y;

p4 = 'Diff : X=' + x + ' Y=' + y ;
document.getElementById('coorinfo4').innerText = p4;

document.getElementById('myBox').style.left = x;
document.getElementById('myBox') = y;

once = 1;



<div id="myBox" style="position:absolute;z-index:100;" onmousedown="PositionFlag=1;" onmouseup="PositionFlag=0;once=0;"><table border=1><tr><td bgcolor=#ddeeff align=center><br>  <font color=orange>orange</font>  <br><br></td></tr></table></div>

<body onmousemove="UpdateXY()" onload="document.getElementById('myBox').style.cursor = 'hand'; = 'crosshair';document.getElementById('myBox').style.left=100;document.getElementById('myBox');">
<div id="coorinfo1"></div>
<div id="coorinfo2"></div>
<div id="coorinfo3"></div>
<div id="coorinfo4"></div>


You will see the XY coordinates displayed with a DIV box with the text orange on it. Simply drag the box around and you'll see the magic.

Let me know if you have any questions regarding the codes as I put very little comments on it. Sorry. Too rush. Gotta go.
Read More »

Monday, December 5, 2011

PHP Date and Time MySQL Management Recommendation

Things are simple if everyone lives in the same time zone. Things become complicated when we want to develop a system that is "international". Time zone is a very important for internet related applications. The following shows the method I like when inserting time and date into MySQL and retrieve from it:

Insert date and time to MySQL

$timezone = "2"; // Get the time zone from user, usually from POST data
// Normalize Date/Time to Greenwich Mean Time (GMT) Zone
// Use gmdate to format to MySQL friendly format
$date = gmdate("Y-m-d H:i:s", time());
$result = mysql_query("INSERT INTO my_table VALUES ('$value1', ..., '$date', '$timezone')");
if (!$result) {
die('Invalid query: ' . mysql_error());

IMPORTANT: Make sure the MySQL field is declared as timestamp data type. Time zone is of integer of size 1.

Retrieve date and time from MySQL

$result = mysql_query("SELECT my_date_time, my_time_zone FROM my_table WHERE my_match_criteria = '".$search_criteria."'");

if (!$result) {
die('Invalid query: ' . mysql_error());

// assume only one row of result is returned. Otherwise, use mysql_fetch_array()
$time_data = mysql_fetch_assoc($result);
$offset = intval($time_data['my_time_zone'])*60*60;
$adjusted_time_data = strtotime($time_data['my_date_time']) + $offset;
$adjusted_time = date("g:i a F j, Y ", $adjusted_time_data);

NOTE: The date/time stored in the MySQL will be displayed according to the time zone saved in the database as well. Please change the column name my_data_time and my_time_zone according to your need. intval() is used to convert the time zone string retrieved from MySQL to integer value to calculate the offset to the time/date stored in GMT format.

With this method, one does not need to worry about the origin of the user. The downside is that the date/time will change whenever the time zone is changed. It all depends on your web app design whether you allow the user to change the time zone after the initial setting.

strtotime() is used to convert the date/time in string format to UNIX time format (integer) so that the offset can be added to it to produce desirable result. Adding offset to a string won't produce the right time-zone-adjusted date/time.

date() is finally used to format the date/time for proper display.

ALTERNATIVE: You can also store the 10-digit raw UNIX time value from time() function and stored as 10-byte integer to reduce the size of your database. Anyway, the MySQL functions related to the timestamp format can't be used for this 10-byte integer data type. It's totally up to your preference whether time manipulation or the size is more important for your app.
Read More »

Tuesday, November 29, 2011

PHP to Convert Binary Data (in String Value) to Numeric Values

$string = "10101011";
echo(stringbin2num($string)); // Will return 171

function stringbin2num($input) {

 $len = strlen($input);
 $count = 0; $val = 0;

 while ($count < $len) {

  if (substr($input, $len-$count-1, 1)) {
   $val += pow(2, ($count));

 return $val;

This function might not be needed in many situations. It's just a reference for those who want to convert string to numbers. You can also modify these codes to handle string of HEX characters such as 'AABB'. If you are reading strings from the binary file, the best is still to use the unpack() function. Unpack function allows you convert to many formats you like.
Read More »

PHP to Write Binary Data (or Array Data) to a File using Pack Function

Writing the Binary Data directly using PHP's Pack() function:

// Write Binary Data
$bin_data = pack("C*", 0x47, 0x49, 0x46);

$fp = fopen("c://test.bin", 'wb'); // replace with your filename
// (please also check file permission before write)
fwrite($fp, $bin_data);

Writing the Binary Data from an Array (if the data length is too long):

// Write Binary Data
$bin_data_array = array(0x47, 0x49, 0x46, .....................................);

foreach ($bin_data_array as $data) {

$bin_data .= pack("C", $data);


$fp = fopen("c://test.bin", 'wb'); // replace with your filename
// (please also check file permission before write)
fwrite($fp, $bin_data);

This WON'T work:

// Write Binary Data
$bin_data_array = array(0x47, 0x49, 0x46, .....................................);

$bin_data = pack("C*", $bin_data_array);

$fp = fopen("c://test.bin", 'wb'); // replace with your filename
//(please also check file permission before write)
fwrite($fp, $bin_data);

Read More »

Facebook Funny Little Trick

There are numerous posts I find it funny.

It is using the Facebook wall to post something funny using the UID such as


After you paste on Facebook wall and it will appear as "Kiss Me!".

It's actually showing the username of the Facebook page "Kiss Me!" and people may not be aware of this when they paste it onto their wall.

But you need to add something like '+' sign to something like @+[84786553145:0] when you send the instruction to paste it to your friends wall and tell them to remove the '+' sign before posting. Otherwise, the "Kiss Me!" will appear in your instruction to your friend instead of the trick codes.

Basically here's the syntax to post username on Facebook wall:

@[Facebook UID:Any Number]
Read More »

Tuesday, November 22, 2011

Global Variable/Array in PHP

The global variable is declared in the function instead of in the main as in C language.


$my_global_array = array(); // Global array set up in main
$my_global_variable; // Global variable set up in main

funtion a() {
global $my_global_array, $my_global_variable;
// declare the array and variable in main as global variable


function b() {
global $my_global_array;
// only takes this global array as the global variable is not needed in this function



Read More »

Monday, November 21, 2011

CSS font used by Facebook

Now the fonts used by Facebook become the favorite for many. If you do a view source, you'll see this CSS setting:

font-family:"lucida grande",tahoma,verdana,arial,sans-serif;
font-size: 11px;

The color tone is not entirely black and it is a bit towards grey.
Read More »

PHP: Setting and Reading Cookies


setcookie("myCookieName", "myCookieValue");

// To read cookie, simply retrieve from the $_COOKIE['myCookieNameToRead']




IMPORTANT: Make sure your <PHP is the first thing is your PHP file. Even a single tiny white space character prior to <PHP will also render the cookie operation useless.
Read More »

PHP: $_REQUEST or $_POST or $_GET?

If you are very sure of the return string type, use $_POST['myStringKey'] for POST data and $_GET['myStringKey'] for GET data.

If you are not really sure (ex. it's from a third party source such as Facebook), use $_REQUEST['myStringKey'].

Read More »

PHP Weird Initialization Criteria

It is weird that before pushing data to an array, one needs to initialize the array before that.

Here's what I did to avoid this weird error (pushed data will be missing):

$my_array = array(); // initialize $my_array is of array type

array_push($my_array, "myTestData1");

If you are used to PERL, this is weird.
Read More »

The Unbelievable PHP Debug Feature: print_r()

There is a function that I personally like very much: print_r().

It prints out the raw data inside a string or array. Especially when dealing nested arrays. It is a function I cannot live without.

When dealing JSON data return from Facebook API/Graph, print_r() can be a very powerful debugging feature especially when the returning data structure is unknown.

Here's an example of examining data returned from Facebook FQL engine:

// Get your access token ($access_token) from OAuth 2.0 procedure

$fql_query_url = '' . '/fql?q=
(SELECT+uid2+FROM+friend+WHERE+uid1+=+me())' . '&' . $access_token;

// FQL query to get all the friends (UID and name) of a facebook user

$user_data = json_decode(file_get_contents($fql_query_url));


Since the returning data structure can be very "nested" (try add in location, hometown, education, ... to the query, you'll see) and uncertain, print_r() is the way to go.

P.S.: Facebook FQL will return a empty JSON data if the return data size is more than certain bytes set by Facebook.
Read More »

PHP Codes to Force a Number to Be a Negative Number

$number = ~abs($number) + 1;

~ is to invert all the bits in PHP and + 1 is to make it a negative number. Remember in CS101 that binary number can be converted to represent a negative number by invert all the bits and +1?

abs() is to make sure it is not a negative number and force it to be a positive number even though it is a negative number. Inverting a negative number will only make it worse.
Read More »

Use JQUERY to blink Texts

<script src=""></script>
function startBlink(){
window.blinker = setInterval(function(){
if (window.blink) {
else {
window.blink = true;



<span class="blink"> Your texts here! </span>

This jquery assumes your background color is white and text color is black. You can change the appearance accordingly to suit your need. The interval is set at 500ms. Adjust the timing accordingly.
Read More »

Sunday, November 20, 2011

The Facebook Avatar Thumb Nail URL[Facebook Profile ID]/picture

This link will be redirected to the actual jpg file in one of the servers of facebook.
Read More »

PHP Code to Convert Unsigned Word (Double Byte, 16-bit String) to Signed Integer

This is useful when one tries to read a two 8-bit unsigned char from binary file and then convert to a signed integer.

The following function is good to convert from 2 character byte string such as 0A, FE, etc., to a signed integer (tested working on both 32-bit and 64-bit Windows 7 IIS environment):

function read_short($s) { // assume $s is an array of (char 1, char 2)

$temp = (($s[0]&0x00ff)<<8) + ($s[1]&0x00ff);

if ($temp & (1 << 15) ) {
$temp = ($temp - (1 << 16)); // fill all bits with 1 from bit 17 onwards

return $temp;

This is the trick to process your 16-bit char (two unsigned char) in 32-bit/64-bit windows PHP environment.
Read More »

Sunday, October 30, 2011

Setting Up A Facebook App Update (Oct 2011)

Here we go:

1) Go to and click on Apps as circled below:

2) If you are here the first time, you will be asked for permission.

3) You may also be asked about your phone number to verify your fb account. Do it before the next step.

4) You’ll see the following wizard if you are here the first time. If you’ve set up any other apps before, you’ll be shown a different page which is the summary of the latest app you last developed.

5) Click on “Create New App” and you’ll see this:

Enter the App Display Name something like “Birthday Calender”. App Namespace is important as it is going to be your app URL:[your app name space]. It’s like email name, the name you chose has to be available on the server before you can proceed. Check the agreement and press Continue after you are done.

6) You’ll see the App Basic Setting page:

The App (Display) Name and the Namespace are already filled up automatically. You just need to fill up the email and also the website. Please leave the http:// out from the App Domain. You just need something like and then press Enter. Please don’t click the mouse instead of pressing Enter. It won’t work. You can also add an icon in A so that it looks more professional.

You also need to fill the Website and App on Facebook. They can be something like:

If you don’t fill up the Secure Canvas URL, you’ll see this warning:

If you don’t have a secure server to run with your app, your account won’t be able to test the app but someone else account can still be running. (as of today 30th of October 2011)

If you don’t have a secure URL set up, you’ll see this when you run your App:

Things change very often and quickly in Facebook. I was allowed to run testing with my account even if I don’t have a secure server to run with a week ago. Now it’s different a week later.

7) Then click on Open Graph on your upper left:

If you run Open Graph for the first time, you’ll see the wizard:

I just put “read” as my action and book as my object. Then I clicked on “Get Started”.

There are 3 parts to it: 1) Action 2) Object 3) Aggregations

I now in Step 3 skipped Step 2 as I've already entered the object in the Wizard window. Anyway, you can change it later on as it is not really important now.

Just press Save and go to the Open Graph Dashboard.

8) Actually the app account is already set up at this point. If you want your app to be able to be published to the public, you’ll need approval. You’ll need to submit your Action (with proper aggregations to back it up) to be approved.

Facebook cannot guarantee that your submission will be approved as your app has to be very “professional” according to the document published.

You can stop here if you don’t need your app to go public.

If so, let’s continue.

Before the submission, you’ll need to get the aggregations set up properly or you’ll see this error after you click on Submit:

“ No Aggregations created for this Action Type. Please create a completed Aggregation populated with sample data before submitting for review.”

In order to avoid this problem, you’ll need at least a good aggregation set up. Click on Preview on the Aggregations section as circled above.

Click on Add New for the Preview Action:

Please make sure you give it a dummy Sample Image by simply getting any image URL and click on the Sample List and a pull down menu will show “Add Custom URL” and a “http://” will appear. Please enter a valid URL anything other than Click on Create after you are done.

Then click on Add New for the Preview Objects. This is the crucial part:

You basically need to fill up everything. DON’T leave anything blank. Click Create after you are done.

Now, here’s the final trick:

Please DO click on the Debug! You’ll see this:

If you don’t see any problem here, you are all set! Go back to the Open Graph dashboard, you’ll see this after you click Submit for the “Read” action:

The error about aggregations is gone and you are now ready to submit your action to be approved by Facebook! Congratulations!

Ya, forgot to tell you how to run the app.

Go here:

You can click on App on the top panel to reveal the summary page. The Canvas Page URL is your App's wall/profile page.

You can also click on "View App Profile Page" on the side panel.
Read More »

Friday, October 28, 2011

Facebook App Using OAuth 2.0 and Open Graph Profile

This is the path:

Note: this is for educational purposes and the look and feel might not look professional.

App Feature:
- Convert your friends' contact info into csv file
- You can configure particulars you like to add to the list (csv file)
- Good for backing up your FB contacts
- The csv file can be opened by spreadsheet software such as Excel and OpenOffice. (You need to follow the instruction to open it correctly)
- The texts are international (support most languages)

Internal Feature (Programming wise):
- It's OAuth 2.0 compatible
- Uses JSON (Open Graph) data format
- Uses FQL to run the data collection (Speed Up the Process)
- Uses Open Graph to get basic info of the user
- Compatible with IE7 (known to have problem with OAuth 2.0)
- Uses scope to open up permissions to gather protected graph info by obtaining the right access tokens
- Runs in PHP only
- UTF-8 compatible
- Email and Phone number will not be supported as FB will deprecate it any time

Special Treat:
- Those who donate will receive the full source code with explanation upon request. Please give me a kick if you really need this source code after you donate. Time is money. Installation Guide will also be provided but you need to run it on your own hosting and FB (developer) account. Hopefully, by obtaining the source code and install on your FB account, you can kick start your FB App development!

The documentation will also address the IE problem. Actually IE is not the culprit as it is just enforcing very strict anti CSRF (Cross-Site Request Forgery) rules.
Read More »

Thursday, October 20, 2011

Javascript to Move the HTML Body Background Image (Shake Like Wave)

Call this wave_background() function and your background will shake like you are underwater. But before that, make sure you have a background image that can mirror to x or y axis. Otherwise, the shake will look ugly.


var xpos = 100;
var wave_timer;
var tmp_string;
var ran_num;
var ran_dir;

function wave_background() {

function move_background() {
ran_num = Math.floor(Math.random()*5);
ran_dir = Math.floor(Math.random()*6);
if (ran_dir == 2) {
xpos = xpos - ran_num;
else {
xpos = xpos + ran_num;
tmp_string = xpos + '';
tmp_string = tmp_string + 'px -100px'; = tmp_string;


Read More »

Monday, October 17, 2011

Add Action to Your Facebook App Before Submission for OAuth 2.0 Open Graph API

Please check out my latest update here:

Some info may not be applicable any more. This latest update also covers the aggregations part in more detail.

Many things have changed since the October 2011. With the Oauth 2.0, access_token is now a must. Even the hosting for the App, App's action and object are now needed to gain the access and approved by Facebook before it can be published to the world.

But I only touch on adding a legal action to your FB app here. Although there is still a long way for an App to be approved. The official doc is here:

But I find it to be a bit out of touch. That's why I decided to blog my experience here so that I can remember what I just did.

You need to fill up the App info completely before the setting up the Open Graph (circle in red). Note that, App Namespace is important and it has to be unique across facebook network. Just like applying a username for an email. Next, you also need to specify a App Domain or your open graph won't work. DO NOT include "http://" or facebook will just ignore your entry. Just is sufficient. Press enter right after the entry and press save at the bottom of this page.

The Open Graph (Circled in Red)
I will only touch on the way I used to add a legal action to the app although there are still steps away from getting an approval for the FB Graph usage on your app.

If you are configuring this for the first time, FB will direct you to a wizard.

If not, you can go to the dashboard to reconfigure. Here's the screen shot:

I use "Bake" as my action and "Muffin" as my object for this example.

Here's the HTML to kick this "Bake Muffin" action to the FB system (not yet approved but you need this initial verification): (I modify from the example in the tutorial and some codes from I got from stackoverflow here and there. Credits go to whoever I copied from pieces here and there)

<html xmlns="" dir="ltr" lang="en-US"

<head prefix="og: [Your App Namespace]:[Your App Namespace]#">
<meta property="fb:app_id" content="[Your App ID]" />
<meta property="og:type" content="[Your App Namespace]:muffin" />
<meta property="og:url" content="[This URL]" />
<meta property="og:title" content="Any title" />
<meta property="og:description" content="Any description" />
<meta property="og:image" content="Any image (url)" />

<script type="text/javascript">
function postkick()
FB.api('/me/[Your App Namespace]:bake' +
'?muffin=[This URL]&access_token=[Your Access Token]','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
else {
alert('Post was successful! Action ID: ' +;


<div id="fb-root"></div>
<script src=""></script>
appId:'[Your App ID]', cookie:true,
status:true, xfbml:true, oauth:true


<font size="30" face="verdana" color="grey"> Kicking Bake Muffin Action </font>

<input type="button" value="Kick In" onclick="postKick()" />


Please pay attention to those in red. Slight mishap may render the entry unsuccessful. Use this HTML and run it from the domain you specify in your App Domain.

You can get the access token from the "Get Code" in your Open Graph Dashboard (Action section). You'll see this:

You'll see this after you click on "Kick In" if it is successful:

If not, you'll get the error message telling you what went wrong.

Good luck!

P.S.: Sometimes you don't need the namespace in here:

<meta property="og:type" content="[Your App Namespace]:muffin" />

Please stick to the "Get Code" from the "Object Type" for your object.

After following the doc, I see this (after clicking "See App Timeline View"):

Maybe this is the reason why I keep on getting error during submission (I do see a dateline of 24th of October 2011 there):

No Aggregations created for this Action Type...

P.S.: Now out of a sudden, I am allowed to press "Continue" in the "Submit an Action Type for Approval". I did nothing special except adding another simple aggregate that shows OK in "The New Auth Dialog".

More tips for Facebook Open Graph aggregation:

If you see those signs, congratulations:

Read More »

Monday, October 10, 2011

About Installing PHP on IIS 7

All tutorials I found online are for "x86 Thread Safe" version of PHP.

If you install the "Non Thread Safe" version, you won't get the php-cgi.exe in your PHP directory.

So far no one points this out yet.

Just in case you need this info.
Read More »

Wednesday, October 5, 2011

About AJAX, JQUERY, JSON, Microsoft AJAX

Ever since facebook embraces AJAX, the popularity surged.

Yahoo and Google started this game and it is good. Microsoft AJAX is having compatibility problems with browsers and JQuery took the center stage.

I summarize the new trends as below so that it's easier to understand:

AJAX - HTML direct connection to server without refreshing a page
JQuery - Advanced Javascript codes to manipulate CSS and AJAX connection/data
JSON - An alternative to XML data format. XML is harder to use.
Microsoft AJAX - JQuery can replace it easily due to its wide compatibility.

JQuery is the winner as it can manipulate CSS and run AJAX stuff. Its partner, JSON, can easily replace XML due to its compatibility with browsers and programming languages. But their concept is all about associative arrays or hash tables. Please don't let the fancy name scare you.

The above shows the difference between "AJAX"ing with JSON and XML.

JSON is very Google/Yahoo feel whereas XML is very Microsoft feel. Hope this is easier to remember.
Read More »

PHP fwrite/fputs Newline Problem in IIS7

The problem I encountered is that I couldn't write a newline to the file under PC environment.

Then I tried this and it worked:

fwrite($fh, "My Text...\r\n");

Instead of just \n, I need to have the \r\n pair under PC environment. No such issue using PERL under PC. Weird.
Read More »

AJAX Using JQuery and PHP to Check Availability of User Name

Again, I compiled these codes from several sources and it's hard to give credit to all of them as some of them I only use several lines and some I only use the concept. Many I found are not fully working. That's why I want to show you the one that's working for me (I'm using PHP5 with Windows 7 via IIS7).

Note: Especially the part JQUERY AJAX pass JSON data to PHP. I don't need to decode the data in PHP. If json_decode() is used, the data will be gone. I really don't know why most examples are decoding the JSON data. But the return of JSON to JQUERY requires the json_encode() to do the job.


userName = $(document.myForm.username).val();

if(userName.length <= 3)
$("#display").text("username must be at least 4 characters");

type: 'POST',
url: 'CheckUserName.php',
data: {
userName: $(document.myForm.username).val()
dataType: 'json',
success: function(response)
if(response.found == false)
$("#display").text("username is available");
$("#display").text("username is already taken");


<form name=myForm>

<input type=text name=username size=35 maxlength=200>

<input type=button name=checkName id=checkName value="Check Availability">

<div id="display"></div>


The PHP (CheckUserName.php) :


$username = $_POST['userName']; // no need to decode JSON

$dblink = mysql_connect(yourhost, 'yourID', 'yourPassword');

if (!$dblink) {
die('Could not connect: ' . mysql_error());


$result = mysql_query("select * from yourMemberNamelist where Username = '$username'");

while ($row = mysql_fetch_assoc($result)) {
$temp = $row["Username"];


if ($temp != $_POST['userName']) {
$return['found'] = false;
else {
$return['found'] = true;

echo json_encode($return);



Again, I put those highlights in red to signify "attention". This is what works for me using IIS7. I'm not sure why there are so many codes out there that is not really working. Maybe it's my IIS7 with PHP5.
Read More »

Free Simple Javascript Password Strength Checker

These codes came from many sources until I forgot the origins. I just combine all the good stuffs I found from the net. Sorry if I use your codes somewhere and remind me to include your credit as I forgot the origin of it.

The Javascript function:

function checkpassword(pw) {

var Score = 0;
var Result = "weak";

if (pw.length>5 && pw.length<8) { Score = (Score+6); }
else if (pw.length>7 && pw.length<16) { Score = (Score+12); }
else if (pw.length>15) { Score = (Score+18); }

if (pw.match(/[a-z]/)) { Score = (Score+1); }
if (pw.match(/[A-Z]/)) { Score = (Score+5); }
if (pw.match(/\d+/)) { Score = (Score+5); }
if (pw.match(/(.*[0-9].*[0-9].*[0-9])/)) { Score = (Score+5); }
if (pw.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) { Score = (Score+5); }
if (pw.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) { Score = (Score+5); }
if (pw.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) { Score = (Score+5); }
if (pw.match(/([a-zA-Z])/) && pw.match(/([0-9])/)) { Score = (Score+5); }
if (pw.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) { Score = (Score+5); }

if (pw.length == 0) { Result = ""; }
else if (pw.length < 6) { Result = "too short"; }
else if (Score < 16) { Result = "very weak"; }
else if (Score > 15 && Score < 25) { Result = " weak"; }
else if (Score > 24 && Score < 35) { Result = "mediocre"; }
else if (Score > 34 && Score < 45) { Result = "strong"; }
else { Result = "strong enough"; }
document.getElementById("yourResultDivID").innerHTML = Result;


<input type=password name=pw size=35 maxlength=12 onkeyup="javascript:checkpassword(this.value);">

<div id="yourResultDivID" style="display:inline;" width=100></div>

The thing to pay attention to is highlighted in red. Something I found many other ways in the net but this is what I like.
Read More »

Wednesday, July 27, 2011

How to Set Facebook Landing Page to Your App?

Can you do this? Yes and no.

Yes, it is only applicable to those who haven't "LIKE" your page/app.

No, if your fan has already "LIKE" you. They will go to the page's wall instead.

You can refer to how to set up the app in my earlier post if you haven't made one yet. If you already have an app in place, you can easily go to your intended facebook page and then click on "Edit Page" in "Get Started" or on the wall on the top right.

You may be landed on the "Manage Permissions" link. If not, go there. Then find your app in the Default Landing Tab options. Your app should be there. After that, save your changes.

Once again, if you already "LIKE" your own, you go to WALL directly. Log out and go the facebook page, you'll be landed on the app you just picked.

Read More »

Create a Facebook iframe App/Tab (Formerly known as Fanpage Static FMBL Tab)

Many changes have been made recently by facebook and here's the official facebook tutorial on this subject:

Many steps in the following are no longer applicable.

Ever since March 11, 2011, Facebook has phased out the Static FBML support and introduced the new iframe App/Tab.

As of today 27th of July, 2011, the following steps are taken to make this work. I cannot guarantee compatibility in the future as Facebook changes its functionality very often.

Note: the FBML is no longer required. BUT you need to have your web page in HTML hosted somewhere and port it into facebook as app using the following method.

Anyway, here are the steps I found it working:

Step 1:

Go to :

If you are here for the first time, you will be prompted for permission like any other Facebook apps.

Step 2:

In the developer's page, click on "Create New App" on the upper right corner. The “New App” mini window will pop out in the middle.

Then, enter App Name, Locale, and agree to the Facebook Terms. You will then be asked to complete a Captcha text recognition after that.

Note: Make sure your Facebook account is verified by mobile phone or credit card or you'll be asked to do so before proceeding further.

Step 3:

You are directed to "About - Basic Info" of this App Profile Edit control panel. Fill up the basic info such as Description, Category, Apps Icon image, Contact info, etc.

You are also given the app id and app secret here.

Step 4:

Click on “On Facebook – Canvas Settings” on the left panel as shown below.

You are then to fill up the App info such as Canvas Page, Canvas URL, Secure Canvas URL, Iframe Size, Bookmark URL, Social Discovery, Tab Name, Tab URL, etc.

The most important part is the Canvas URL which points to the URL you want it to appear in the iframe of facebook.

Remember the “http://”. The web address has to be complete. You can also include query strings in the URL but they may be treated as POST string but send with GET format. A bug that facebook has to fix someday. If you are using PERL CGI lib to capture the form data, you may need to do some tweaking.

Someone mentioned that the URL has to end with a "/". Not sure about that.

The 2nd important part is the Tab URL, it is like PATH to the Canvas URL. For root access to the web page, you may be tempted to leave it blank. But I advise you to put a “&” sign there. Leaving it blank may cause error and your app won’t show up.

Step 5:

Click on "View App Profile Page" on lower left of the facebook developers page (as shown in the image above also). You can test your settings to see if there is any error by clicking on the ”Go to App" button on top in your App Profile Page.

If it is working, you can port the app to any of your facebook page. Just click on "Add to My Page" (as shown below). Walla!

You may need to obtain permissions to your app by getting an access token. A simple click will do if you are asked to get one.

If you make a mistake somewhere, you’ll get this error which means you need to go back to (click on Edit below “Create New App”):

The app "xxxxxxxxxxxxxxxxxx" is temporarily unavailable due to an issue with its third-party developer. We are investigating the situation and apologize for any inconvenience.

In fact, I have no idea. I can only see the link on the left but the Tab is nowhere to be found. Facebook may be eliminating the Tab on the wall altogether. Sorry for not being able to provide further info here.
Read More »

Wednesday, May 25, 2011

My Best Way to Place favicon.ico for All Browsers Type

Favorite Icon (favicon.ico) can help boost the professional look of your website.

But somehow different browsers support it differently. Here are the codes I use for maximum compatibility:

<link rel="icon" href="/favicon48.ico" type="image/ico"> <!-- for Mozilla based browsers -->
<meta name="msapplication-task" content="name=YOUR_ICON_NAME;action-uri=./favicon32.ico"> <!-- for IE9 -->
<link rel="SHORTCUT ICON" href="./favicon32.ico" type="image/x-icon"> <!-- for IE8 -->

Besides you also need to place a 16x16 small icon named favicon.ico in the root path of your server to be compatible with IE5/6.

Size? I would say make each of those sizes: 16x16, 24x24, 32x32, 48x48, ... just in case future IEs can use them.

What software to make them? I use Photoshop with plugin to export .ico file.
Read More »

Sunday, May 22, 2011

How to Configure Facebook Share (fb-sahre) Thumbnail & Texts?

Update on 18/12/2014: The latest version has been updated here.

This could be something a lots of new web developers wanted to know as Facebook is gaining substantial popularity each day.

If one can share its web content to Facebook, it could mean a big help to the marketing of the website.

The link you need to put the Facebook link (<fb-share>) to your website or blog:

<script src=""></script>
<script src="" type="text/javascript"></script>

<meta property="og:title" content="Your Title" />
<meta property="og:type" content="website" />
<meta property="og:image" content="Your Thumbnail Image Link" />
<meta property="og:url" content="Your URL" />
<meta name="description" content="Your Description" />


<a name="fb_share" type="button_count" href="">Share</a>

You can also configure the font for the "Share" text.

IMPORTANT Note: If you make a mistake somewhere in your code, you need to go to Facebook URL Linter to refresh the fb-share information of your page. If not, it will be stuck at your first submission as it is cached in Facebook server for future use until you run this Linter. I also heard it will be rerun 24 hours later. I did not take this chance to wait for another 12 hours to do another round of debug. Going to this lint link should be the easiest way to debug your fb-share link:
Read More »

Saturday, April 2, 2011

Web Browser Usage Statistic/Market Share/Popularity

Out of my curiosity, I just check the latest stat:

To my surprise, IE is losing steam quite a lot and it is being neglected as days go by. Although Firefox is the most popular browser as of today, 2/4/11, the trend may skew towards Chrome in the near future. Good job! Google!

I expected Safari to go higher due to the popularity of iPad. But to my surprise, iPad doesn't bring much to Apple in terms of the popularity of Safari used in every iPad.

Yes, surprise, surprise and surprise.

Update (April 5th, 2016): Yes, Chrome is indeed now the winner and it is even far in the lead. Kudos! Chrome!
Read More »

Tuesday, March 22, 2011

For IE, Don't Put CSS Style inside <TABLE>

Anything CSS style setting you put inside <TABLE> will turn into something unpredictable.

Put inside <TD> instead!

For Chrome, Firefox and Safari, they are OK if you put CSS style setting you put inside <TABLE>!
Read More »

Monday, March 14, 2011

Make ASP - ADODB using MS Access MDB file to display Chinese text via UTF-8

You need this:

Response.CodePage = 65001

somewhere in your asp code. Tada!

Of course you need this in the HTML header:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Complete list of codepage can be found here:
Read More »

Saturday, February 12, 2011

How to get your unique Facebook URL?

Won't be able to find easily on facebook.

You need to go here directly after logging to your facebook account:

Very obscure and discouraged way to create a unique facebook URL of your account. Don't know the reason why but it could be to avoid abuse.

Warning: Remember, you can change your username only once!
Read More »

Configure your FB Likebox using CSS

Update on 31st of January 2013

This method is no longer supported. (Although the CSS names and values are still valid) Please refer to this latest method to link to the external CSS file instead:

Requirement: You need to have a facebook fan page and are able to get its profile_id as explained earlier.

Use this:

<script src=""></script>

<fb:fan profile_id="NNNNNNNNNNNNNN" width="292" height="580" connections="10" header="true" stream="true" css="http://url..../filename.css?1"></fb:fan>

You can adjust the width, height, connections, header, stream, any way you want it but do make sure your css file is located somewhere in the net and can be accessible online. DO NOT point the css to a local file. It won't work. The ?1 is just a variable to tell the browser not to get from the cache. You may need to change it to ?2 or ?3 .... each time you want your browser to reload the css file or it won't be read as it will be taken from the cache of your browser. Any number will do as long as it's not been used before. If you don't want the browser to reload the css content, just leave out the ?1 URL GET/POST data string.

Here's an example of the css to configure your facebook like box or fan box or whatever box to be called in the future.

.full_widget {
opacity: 0.9;
.fan_box .profileimage, .fan_box .name_block{
display: none;
.fan_box .connect_action{
padding: 0;
color: #FF6600;
font-weight: bold;

Basically .full_widget is the entire fan box body. I set it to 90% transparent as I wanted it to show 10% of the background.

.profileimage is your avatar. If you don't want it to show up, set it to none like above.

You can refer to an example css settings here. Note: I do not own these css codes.

Update on 31st of January 2013

This method is no longer supported. Please refer to this latest method instead:

Read More »

How to build Facebook Like Box

This is the method as of today as Facebook changes its features very often:

0) Make sure you have a FB fan page

1) Go to Account -> Use Facebook as Page (Used to be called Manage Fan Page)

2) A window will pop up in the middle asking you to choose the page which you want to go to manage

3) Click Edit Page on the top right on your Fan Page

Note: Pay attention to the ID on your address bar (URL), something like


4) Click on Marketing and then "Add a Like Box to Your Website"

5) Replace the Facebook Page URL with:
where id = [the id of your fan page which you can view on the address bar when you are in step 3.

Then click on Get Code.

6) You can get both iframe and XFBML codes. Usually you only need iframe codes for your website. XFBML is for facebook page.

Read More »

Sunday, January 2, 2011

IE7 & Img Onload Weird Combo (Doesn't Work and also Work)

<img src="" onload="javascript:xxx();">

It won't work in IE7 with Doctype set to transitional. But it works fine with or without Doctype set to transitional in IE8.

It also doesn't work with iPad's Safari but works fine with PC/Mac Safari.

The exclusive IE7 sniffer I like best:

if (navigator.userAgent.indexOf('MSIE 7') != -1) {
// Your action here!!!
Read More »