Saturday, March 14, 2009

Basic AJAX code

If you want to have an AJAX application, this simple code is what you must have first.

var xml = make_xml();
function make_xml () {
if (typeof XMLHttpRequest == 'undefined') {
objects = Array(
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.5.0'
);
for (i in objects) {
try {
return new ActiveXObject(objects[i]);
} catch (e) {}
}
} else {
return new XMLHttpRequest();
}
}
Save the code in "ajax.js" and call it in your HTML <head> section like this:
<script language="javascript" type="text/javascript"
src="ajax.js"></script>
Next, you need to have a handle to handle submitted forms like this:
function handle_submit () {
xml.open('post', root + '/');
xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xml.onreadystatechange = function () {
if (xml.readyState == 4) {
data = xml.responseText.split ( "[BRK]" );
get('div1').innerHTML = data[0];
get('div2').innerHTML = data[1];
} else {
get('div1').innerHTML = 'Please wait';
get('div2').innerHTML = 'Please wait';
}
}
if (window.encodeURI(get('action').value) == 'action1') {
xml.send('action=' + window.encodeURI(get('action').value) + '&javascript=1&
field1=' + window.encodeURI(get('field1').value) + '&field2=' +
window.encodeURI(get('field2').value));
} else if (window.encodeURI(get('action').value) == 'action2') {
xml.send('action=' + window.encodeURI(get('action').value) + '&javascript=1');
}
return false;
}
In order to save time, I prefer to replace the long "document.getElementById" with a simple get() function, like this:
function get (id) {
return document.getElementById(id);
}
Next, you need to have a handle to load onsubmit action, like this:
function load_handler () {
get('action1').onsubmit = handle_submit;
}
Don't forget to call the handle during page load, like this:
window.onload = load_handler;

Using this basic AJAX code, you may do all the web interactivity using AJAX, easily.

All the other codes didn't change at all, including HTML forms, PHP codes, etc. All you have to do is just synchronize the ID's of your HTML forms with your "ajax.js" ID's, otherwise it won't recognize your request.

Any questions, please write on the comment form. Good luck!

Thursday, January 22, 2009

Happy New Year!


I'm writing this post to wish my Chinese friends a Gong Xi Fa Chai!

I also wanted to say sorry for not writing new codes to you. This is because I'm currently too busy doing my "Mega Project" for my big client.

I'm hoping to write more tips and tricks in programming more consistently.

Have a good day! :)

Saturday, November 29, 2008

I am still alive

It has been a while I didn't update this blog, since I was too busy managing a sports event at my place.

Today I'm not going to post anything about PHP functions. Instead, I would like to give a big thank my loyal readers on being such a concern asking me if I'm still alive.

I'm telling you guys, I'm still alive healthily and happily right now. I won 4 medals in the annual event — gold medals for badminton and rope pulling, silver medals for volleyball and soccer. What a worth busy moments!

After all, thank you for being so patient waiting for my updates. I'll definitely update this blog soon.

Saturday, October 18, 2008

Fortunate vs Unfortunate

My hard disk crashed, totally damaged. This is real sick.

Fortunately it is still under warranty. Unfortunately it takes too much time to be replaced.

Fortunately not more than a month to wait. Unfortunately I lost all my data.

Fortunately I got backup. Unfortunately the last one was about three months ago.

Fortunately I can get back all my PHP applications. Unfortunately not the latest one.

Fortunately I can get back my MySQL data, too. Unfortunately not the latest one, too.

Fortunately I can set back my work after the new one arrived. Unfortunately I didn't backup all my software as they eat lots of disk space.

OMG, I don't know what to do, where to start, how to complete. It's real hard.

What do you think when fortunate vs unfortunate. Which one wins?

Saturday, September 27, 2008

Prevent accidental window closing: alert onbeforeUnLoad

Today, I'm going to show you how to stop your visitor to close window of your site, using JavaScript.

It's useful when they have unfinished processes, or unsaved data, in which they whether accidentally or deliberately clicked on the close button of your page.

It's also useful for your marketing strategy, like one-time offer, final discounts, and so on.

Simple. First, use this following function. Then I'll show you with 3 situations for example.

<script>
var askFirst = false;
function preventerOn() {
askFirst = true;
}

function preventerOff() {
askFirst = false;
}
window.onbeforeunload = sureUnload;
function sureUnload() {
if (askFirst)
return "Are you sure you want to exit this page?";
}
</script>


Situation 1, if you want to prevent window closing from the beginning, you may want to use the body tag, like this:

<body onload="return preventerOn();">


Situation 2, if you want to prevent window closing when your visitor enter something in a form, use it like this:

<input type="text" name="input1" onchange="return preventerOn();">


Situation 3, if you want to prevent window closing before reached an amount of time (i.e: 20 seconds), you may add this one to the script above:

function setTimer() {
preventerOn();
setTimeout("clear();",20000); // 1000 is for 1 second, so 20000 is for 20 seconds
}
function clear() {
preventerOff();
}


You may need to change in the body tag, from this:

<body onload="return preventerOn();">


to this:

<body onload="return setTimer();">


That's all.

If you have any questions regarding this, please feel free and don't hesitate to ask me through the comment form.

Thank you.

Monday, September 22, 2008

More elaboration on 'signed-by' and 'mailed-by'

A friend of mine, Tim recently asked me about the mail function in PHP programming which I wrote on how to edit or remove the default 'signed-by' or 'mailed-by' label during the sending activity.

His question is, where to put the code? As far as I'm concerned, I was not talking about the code, or even code positioning.

I'm talking about a particular technique that we would use in order to edit or to remove the distracting label when we use mail() function in our code (programming).

The real situation yet to be explained
The default value for the labels is usually the domain name of the server hosting company we run from.

In example, let say you use a web hosting from the well-known BlueHost company. Then you planned to send mass email to your friends about your new site, without revealing your friends' details among them.

So all you need to do is having your list in a database, and then use loop function to send mail to them, one by one, using the php mail() function. Perhaps, you'll use a fake email, or your self-hosted email, or even your true email from Google mail or Yahoo! mail.

Unfortunately, when using this method, recipients will see the header (if they checked on it) of the email, stated that the mail you sent was mailed by (in example) mailserver#.bluehost.com.

This is what we don't like to see. It'll tell the recipients what hosting service we are using.

So, in order to remove or edit the default value, we need to do those things that I explained earlier. To see the post, click here.

I hope my friend Tim will get what I was actually saying. What say you?

Friday, September 19, 2008

Edit or remove 'signed-by' or 'mailed-by'

Recently I was trying to remove the labels 'signed-by' or 'mailed-by' which displayed the server name of my web hosting company when I do mailing activities from PHP script.

I was actually wanted to have my domain or perhaps my 'fake' domain address to be there. I don't want to display the web hosting company.

The labels are like distracting me as a mailer, because I don't really need that to be displayed. They're like disturbing my privacy.

After having some research, I finally found the answer. There's actually five arguments in the mail() function, instead of just four like this:

mail($mailto,$subject,$message,$header);
The fifth argument is the answer to my question. I believe some of you might get in the same situation.

So lets get straight to the point. Choose one of these below:
  1. You want your domain to be displayed; or
  2. You want nothing to be displayed.
You can't have them to display other than that. I.e: You want it to display 'signed-by: google.com' or 'mailed-by: yahoo.com'. No you can't have it. Just choose one of the stated above.

If you want the first choice, do this:
  1. Create an email address from your domain, or take one you've had, like admin@yourdomain.com.
  2. Set your code like this:
    mail($mailto,$subject,$message,$header,'-f admin@yourdomain.com');
  3. There's no number 3, you're done!
If you want the second choice, you only have to do the second one in the first choice. You may change the 'admin@yourdomain.com' to any email you'd like, i.e: myself@yahoo.com.

Easy, huh?

Wednesday, September 17, 2008

I'll be continuing from now on...

I've paused my blogging activity for such a long period. I think I have to go back to work, from now on.


Recently, I signed up for EntreCard. I wanted to see how exactly this program works. If I find this social networking tool helping me much i building my personal ranking, I would stay. Otherwise, I'm moving away. 

So let's give it some time. Maybe I should try this for about a month or two. What say you? 

Thursday, October 18, 2007

Save Time on Submitting Forms

I always involved in making applications that submit forms to databases. In order to save time, I just copy this function to all my applications - because they're a great time saving function that suits all my applications. Here I'll show you step by step on how I made the function:

(This is the form example)

<form method="post" action="/process">
Input 1: <input type="text" name="input1">
Input 2: <input type="text" name="input2">
Input 3: <input type="text" name="input3">
<input type="hidden" name="action" value="submitForm1">
<input type="submit" value="Submit">
</form>

Note two important things in the form above:
  1. action value; and

  2. form action

The action value will ensure the form to be submitted the right way whereas the form action will lead itself to index.php.

In the index.php, I set a condition - switch ( portion(1) ) case "process";.

The "process" condition goes like this:

<?php
if ( isset($_POST['action']) && $_POST['action'] == "submitForm1" ) {
  if ( submitForm($_POST) ) echo "Successful!";
  else echo "Failed!";
}
?>

Do you realize - I sent the data using array - $_POST array! This is what I'm talking about. Sorry for the long intro... :P

Ok now let's see what is inside the submitForm() function. In brief, the function must contain:

  1. key assigning process for each input value;

  2. character control using str_replace function;

  3. additional controls and conditions; and

  4. SQL statement structures;


I set the head like this:
function submitForm($post,$additional_input='',$unwanted_input='')

Now we've covered the main concept and some code go through. I think I've to stop here for now. See you in Part II!

Wednesday, October 17, 2007

How to Customize Ugly Link Structure

By default normal PHP driven websites use web URLs which have question marks and lots of numbers in them. This situation will cause an ugly and hard-to-remember link. It will also blinds the search engine to index your page.

However, if you're using a linux hosting (including EasyPhp for windows) you actually have the ability to create a custom URL structure for your links. This can improve the aesthetics, usability, and forward-compatibility of your links. You can also hide your programming language, set the .php to .html, and many more.

Here I'll show you how to create a beautiful SEO friendly links using .htaccess.

First of all, you need to make sure that your hosting company has enabled mod_rewrite module. If you're using EasyPhp server, you just need to do some modifications to your Configuration » Apache file called httpd.conf. Find the word mod_rewrite.so and mod_rewrite.c - uncomment both lines. Save and you're done with server setting. But if you're using xampp server, you may explore them yourself as I'm not really in to it.

After that, you need to create a .htaccess file in your root directory of your website. Note the dot(.) in front of the file name - it shows that the file is hidden in linux file system.

Open the file in your editor's mode (i.e: Notepad, Dreamweaver, cPanel Code Editor etc) and write this code to the file and save:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Note that from now on, all unknown physical links will lead to index.php. All you have to do now is to create a function that handles all the portions after the slash of the site root as a virtual link. If you're confused, let me show you an example:

Link: http://yourdomain.com/show/my/camera/canon/40d/

Here, yourdomain.com is your site root.

The words after the first slash, 'show', is your first portion, 'my' is your second portion, 'camera' the third, and '40d' the last. That's what I'm talking about. I guess you've got it by now.

Back to the function. I always use this function to tell the system where it has to go:

This one is to return the value for each portion:
function portion($int) {
  if ( !defined('URI') ) define('URI',$_SERVER['REQUEST_URI']);
  $uri = explode("/",URI);
  if ( !@$uri[$int] ) return false;
  else return $uri[$int];
}

And this one is an example on how to set them to go to a certain page:
if ( portion(1) == "show" ) {
  if ( portion(2) == "my" ) {
    if ( portion(3) == "camera" ) {
      if ( portion(4) == "canon" ) {
        if ( portion(5) == "40d" ) There goes your additional code to show that Canon 40D Camera!;
      }
    }
  }
}

Note that all the ifs are for the example only. I don't do programming like that in the real scenario.

Now, you're free to customize your links. Remember, all the virtual links will be redirect to the index.php. So it's your creativity to structure them.

If for me, I always arrange the portions to a sequence like this (from the very first slash after the domain to the far right end):

  1. main action like display, process, add, update, delete, etc;

  2. type of view like list, detail, etc;

  3. the category ID - if needed;

  4. the sub-category ID - if needed;

  5. the item ID;

  6. any additional needs, and so on..


Anyway, that's just my idea. You may structure them the better way.

Have a good day!

Tuesday, October 16, 2007

Popup Box Solutions - Alert, Confirm, Prompt, etc.

If you're facing a Javascript pop up (or so spelled as popup and pop-up) box problems like this:

  1. my pop up box appeared in different colors and borders an so on - depends on visitors' PC;
  2. I don't like the annoying sound when a box pops out my visitors' Internet Explorer (IE);
  3. I don't like the title bar showing [Javascript Application] in my visitors' Mozilla Firefox;
  4. it doesn't suits when my pop up confirmation question answered using 'Ok' or 'Cancel';
  5. I want to prompt a password before submitting a form but the password characters can be seen,
you've come to the right place because here we're going to discuss about:
  1. how to create a nice, simple and light pop up box;
  2. how to overcome or stop the annoying sound when a box pops out your IE ;
  3. how to set a nicer title on your boxes when using Firefox - instead of [Javascript Application];
  4. how to set a Yes-No or Yes-No-Cancel instead of Ok-Cancel confirm box;
  5. how to set password input type in classic javascript prompt box;
  6. how to pop a box out in almost any desired looks and feels that you've ever imagined of?!
What you're really need to understand in the first place is - The Concept - because this will make you understand WHAT actually happened and HOW is it happened when you're trying to perform a pop up boxes. By understanding the concept, you'll never forget how to make them in the future. (Don't be like me - always forgot again and again)

Pop ups basically work like this. Pop up box that you wanted to display is actually has been preloaded when loading process happen. It's just that it is being hidden by javascript. When somebody hits an appropriate button, the pop up box will visible.

So when you're building a pop up box, you'll basically have to put up a pop up script like this:

<script>
function myPopUp() {
  alert("This is an alert pop up box");
}
</script>

or this:

<script>
function myPopUp() {
  if ( confirm("This is a confirm pop up box") ) return true;
  else return false;
}
</script>

or this:

<script>
function myPopUp() {
  if ( prompt("This is a prompt pop up box") == "value" ) return true;
  else return false;
}
</script>

whereas the activation button will be like this:

<input value="Hit me" onclick="return myPopUp();" type="button">

When you're facing any of above problems and wanted to be like any solutions stated above, you're recommended to change them to a css pop up box, like this:

First, set the style like this:

<style>
.black_overlay{
  display: none;
  position: absolute;
  top: 0%;
  left: 0%;
  width: 724px;
  height: 568px;
  background-color: black;
  z-index:1001;
  -moz-opacity: 0.8;
  opacity:.60;
  filter: alpha(opacity=60);
}

.white_content {
  display: none;
  position: absolute;
  top: 200px;
  left: 150px;
  width: 400px;
  height: 100px;
  padding: 16px;
  border: 16px solid #900;
  background-color: white;
  z-index:1002;
  overflow: auto;
}
</style>

Then, set the box like this:

<div id="light" class="white_content">

Here, put any type of your desired pop up box message freely using any HTMLs like form, input, textarea, select, etc.

Don't forget to put your close button like this:

<a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none'; document.getElementById('fade').style.display='none'">Close[x]</a>

Remember the closing div too:

</div>

And also a background to disable the page while the pop up box is on:

<div id="fade" class="black_overlay"></div>

And last but not least, the activation button - will be like this:

<input value="Hit me" onclick="document.getElementById('light').style.display='block'; document.getElementById('fade').style.display='block'" type="button">

That's it, and you're done!

P/s: This box has been successfully tested on IE5, IE6, IE7, Firefox 2.0, Netscape.

Monday, October 15, 2007

Why Did I Build This Blog

First of all, welcome to my blog. Make yourself at home. Don't hesitate to ask anything about programming. I'm here to try to share all my tips and tricks about programming as well as trying to help each other - including the lucky YOU...

After 10 years of programming, I finally feel how important is it to blog about all my development, problems, and solutions towards programming. Anyway, this blog only suitable for beginners and a bit advance programmer. If you're an expert programmer or so called GURU, this place is not for you. Please leave this place, go and find another place. Not this one - It's nothing if compared to you, experts :P

Why I build this blog? After a decade, I finally realize that I'm losing so much of my tips and tricks about programming. When I tried to find some solutions on the net - when I found them - use them - and then just let them go. As a result, I forgot how to do this and that. Poor me.

Like others said, experience is expensive. It's priceless. Unfortunately, what has gone will remain gone. Here I stand, to rebuild from scratch, step by step - my personal collections of programming solutions.

Cheers,
ImamKhalid