Action confirmation with JavaScript

Just a simple little trick for confirming with a user before they undertake an action on your web page. Sometimes you need to confirm things. You know, does the user of your site really want to delete that file FOREVER, or not. You can do it the hard way with a catch page to confirm, but the easier way is to use JavaScript.

Just like this:

<a href="irrevocable-action.php?doitnow=yes" onclick="return confirm('Are you really, really, really sure you want to do this?')">Do It!!</a>

When the user clicks the link, they will hit a pop up box, displaying the confirmation message and two buttons. If they click yes the link is followed and the action completed, otherwise they stay on the page and nothing happens.


Preventing window close with JavaScript

Closing a browser window with JavaScript is easy, you just call window.close(); however catching the browser close event and preventing it is another kettle of fish. I’ve been working on this a bit on-and-off, and have managed to pull together what I think is a reasonable solution [NOTE: this does not work in Opera, as it uses the onunload() and onbeforeunload() events, which are not supported by Opera 11].

The solution I have come up with is pretty simple once you see it. I put the following code either in my JavaScript library included into the page, or I just place it at the top of the required page (in tags, of course):

function checkClose() {
    if (ok) {
        return "Have you saved your information?";

var ok = true; // this is reset everytime a new page is loaded

function okToLeave() { // called if leaving the page is needed
    ok = false;

window.onbeforeunload = checkClose;
window.onunload = checkClose;

and in my links where I’m happy to leave the page without checking (i.e. on submitting a form):

I have also allowed for a cancel event, where I don’t want the checkClose() event called, but I still want to catch the close/departure:

What we have going on here is a standard JS being called whenever there is a page unloaded. This can be due to clicking a link, entering a new URL in the browser, or closing the window or tab. The JS call will be to checkClose(). If checking before exit is required, then the pop-up is activated. If the page-exiting event is not a problem, then the JS inserted within this event (onclick="okToLeave();") sets the checking variable (ok), which then causes the checkClose() function to do nothing, so the onunload events are not thwarted. In some circumstances (i.e. the Cancel button being clicked) we don’t want the onunload event called, but we do want to confirm departure; in these cases the extra JS inserted in the event (onclick="okToLeave(); return confirm('Confirm leaving this page.');") warns and confirms with the client user.

This approach is only necessary if you are trying to check for events not triggered within your own page (e.g. the window closing event), otherwise it is just overkill. If you only want to confirm when certain links are used, then insert the check within their use, i.e.:

<a href="otherpage.html" onclick="confirm('Do you really 
             want to leave this page?')" >this is a link</a>

I did like this comment I found on a forum regarding this concept though:

The question is not how but why??
If a user wants to close his browser, that’s his god-given right!

If you don’t want him to close it, make it so there’s something interesting in the window. (Naked women seem to do the trick for a lot of people)

client-side time with PHP and JavaScript

As part of upgrading functionality and statistical delivery with I’ve been looking at utilising client-side time. Obviously, PHP and other server-side languages do not have acces to this information. The solution is to use JavaScript and the ‘page-in-between’ method:

	$vars = "?";
	foreach($_REQUEST as $key => $val) {
		$vars .= $key."=".$val."&";
    echo "<script type=\"text/javascript\">"; 
    echo "localtime = new Date();"; 
    echo "document.location.href = '".$PHP_SELF.$vars."client_time=' 
            + localtime.getTime();"; 
    echo "</script>"; 
    // Process page as normal 

What this does is first check whether we have been given a parameter “client_time”. If we have, everything is grand and we can nmove on to rendering the page. If not then we need to iterate through all parameters/variables passed through to the page (either $_POST or $_GET [which has security implications – to be discussed]) and keep track of them as a string formatted for passing through a URL.

Then we use PHP to write a JavaScript function to the page before anything else. This script (running on client-side) gets the client’s current date and time (localtime = new Date();) before redirecting the browser to the same page ($PHP_SELF) with parameters appended ($vars."client_time=' + localtime.getTime();").

Then end result of this is that the client returns to the page, but this time brings with them their (client-side) time for use within your (server-side) functionality.

** Security Issue **

As I mentioned, there are security implications to this approach. By passing all $_REQUEST parameters through the foreach() loop and passing them back through as $_GET parameters (as they are contained in the URL itself) they are all visible and able to be manipulated by the client user or anyone who wants to. Any hidden parameters (ie $_POST) are made visible in this method. If you don’t have any $_POST parameters, or they are not security issues, then this should not be a problem; if there are secure parameters, then this method will not work for you.

If you want to use the time as a parameter, and the page request is coming from a form on another page of yours (hence the $_POST parameters), then you should add a hidden field to THAT form as so:

<input type="hidden" id="time" name="client_time" 
          value="a6d27182b9803699dc15f56e9c0e8eb4" />

with the following script being called at onload():

<script type="text/javascript">
function loadTime() {
var localtime = new Date();


<body onload="javascript:loadTime()" >

and then call the variable from there on the new page like so:

$clientTime = $_POST["client_time"];

This solution is more elegant than the ‘page-in-between’ method, and does eliminate the security weakness discussed.

Dynamic JavaScript population

Today I’ve been fiddling with adding options to a drop down list box dynamically using JavaScript (client side). Because this uses JS, it can also be conditional in terms of the options passed to the list (similar to using PHP on the server side to generate the options for the drop down list box dynamically).

The main function creates a new ‘option’ object and assigns values and text part of the option. This is the engine of that below:

function addOption(selectbox, text, value) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;

Note that each time the function is called, it adds a new option to the list box. So we can add one option by calling the function once. Like this:

addOption(document.drop_list.week_list,"Monday", "Monday");

This way we can create a drop down list box of all the days of the week by calling the function each time for each day of the week. With this now you can easily create the list box. Efficiency then dictates that we should add another step to this by using one array of days of the week. So from the array of days we will loop through and add each day to the list box. Here’s the array set-up:

var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday",
                               "Friday", "Saturday", "Sunday");

Now our array is ready with data, we will loop through the array by using for loop and then call the addOption function using the data of the array:

for (var i=0; i < days.length;++i) {
	addOption(document.drop_list.week_list, days[i], days[i]);

You can see with this array we will able to populate the drop down list box of days. Here is the simple code for html body tag and the form with drop down list:

<title>Dynamic List Population Example
function addOption(selectbox, text, value) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;
function addOption_list() {
	var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday",
                                       "Friday", "Saturday", "Sunday");
	for (var i=0; i < days.length;++i) {
		addOption(document.drop_list.week_list, days[i], days[i]);
<body onLoad="addOption_list()"> 
<form name="drop_list" action="yourpage.php" method="POST" >
<select name="week_list">
<option value="" >Week list</option>

my iPad app round-up

So, I’ve had my iPad for over a month now, and I felt it was time to review the apps I have on it now. I figure a month is enough time to settle into my usage patterns and have discarded apps that just didn’t do it for me afterall.

1: Social Networking –

I don’t run one app for all my social networking, some people prefer to but I have found it better to have apps that focus on one thing, and do what they do do well. For Twitter, I was originally using Twitterific, and had just upgraded to the paid version the day before Twitter released their own app. Since then I have been devoted to the official Twitter app which is clean, intuitive, and just pretty much perfect in my book.

For Facebook, I am still floating between two apps; Friendly and the official Facebook iPhone app. Both are pretty good, Friendly is more aesthetically pleasing due to being designed for the iPad form-factor, while the official FB app seems a little more intuitive and “like” Facebook itself (as you would expect).

I’m also running FourSquare on my iPad, as I don’t have an iPhone (still!!).

2: Utilities / Lifestyle –

I have quite a few utilities set up on my iPad, for news I am running the fantastic NYTimes app, the TVNZ News app, and the NZ Herald app. I also use GeekNews to pull all my geeky tech blogs together into one streamlined place. The Mashable! app is great for a quick check up on what is trending or popping up online currently.
I am currently using PrinterShare for printing directly from the iPad on my home network. This will hopefully change when iOS4 is released for iPad (rumors indicate late November 2010 maybe).
I also have Google Earth, the IMDb app, and a great tracking app – Parcel – which allows you to just put in your tracking code allocated to the delivery you are expecting. Saves having to visit different websites and remember your tracking numbers for different companies. Some other little gems are:
– The WordPress app for blogging on the go
Then for a bit of creative fun, I have GrooveMaker and Drums! GrooveMaker lets you mix tracks, and even create your own tracks on the fly. Drums! is just that, a complete drum set on your iPad – in fact, it’s actually three complete drum sets, as you can choose between Standard, Groove, and Acoustic kits. The sound is true to life, so go get it.

3: Web Dev –

A few free web-dev helpers tucked on the iPad too. I’ve got JsAnywhere and three great apps from Interactive Blasphemy. JavaScript Anywhere is a JavaScript tool which enables you to edit your JS script, adjust the CSS, and then view the results in an HTML page. You can email the results to yourself. From Interactive Blasphemy I have robots.txt, which is just that, a robots.txt generator; Password, which generates passwords of random characters of length and complexity specified; and RGB/HSB/Hex, which enables you to create that perfect shade for you web job, and also then suggests good matching and contrasting colors.

4: Games –

Yep, the main reason most people have an iPad. I am personally a big fan of the logic/strategy games. I’ll list them all, then comment on a few of them, with more in-depth reviews being added, along with links to the iTunes store, later on:
– iFighter – essentially the classic fighter game 1945 remade for the iPad
– Harbor Master
– FlightControl HD
– Canabalt
– Gravity Hook
– Angry Birds
– Angry Birds (Halloween Special)
– Cut the Rope
– Pocket Frogs
– Plants vs Zombies
– Fruit Ninja HD
– Steve Young Football
– Build-A-Lot 2
– Blue Block
– Crazy Traffic: Crashed XL
– Train Conductor 2: U.S.A.
– No, Human
– Trainyard
– UFO On Tape
– Railway
– Chicktionary
– Fish Eat Fish
– Dismount
– GearedHD
– Air Hockey
– TicTacDojo
– Little Metal Ball
– Soosiz HD
– Physics HD
– Gravity HD
– Tilt to Live HD
– NinJump
– Red Bull RC
– Asymmetry
– 8Bit Rebellion (the Linkin Park game)

Surprisingly enough, I have found my usage of the iPad to be alot different than I planned for. I have found the games an easy way to take a 5 minute break when I need to, but have found that I actually now tend to jump on Twitter or a news site when I want a 5 minute chill out. I am still just working with iBooks as my book-reader and PDF-reader of choice. Primarily because I have no need of the flasher features of the other readers out there. Overall, I have to say that the iPad is proving itself to be very worthwhile as a tool; and I keep finding new ways for it to excel and prove it’s worth.

embedding Javascript in PHP

One of the less known uses of external JavaScript is the ability to reference a PHP file instead of a .js file. This does seem to breach scripting etiquette, as we all "know" that server side and client side scripts are prohibited from interacting. Well, it turns out superficial exchange is allowed. Using external JavaScript, you’ll see how PHP and JavaScript can work together in a way you may not have thought possible, and to the great benefit of JavaScript.

The syntax to referencing a PHP file using external JavaScript is consistent enough with what we already know:

<script type="text/javascript" src="myscript.php"></script>

where myscript.php is either an absolute or relative path to a PHP script instead of the usual .js file. You can even pass parameters to the PHP script through the URL string:

<script type="text/javascript" src="myscript.php?param1=bob&param2=thomas"></script>

Your PHP script can then get to these parameters using the global variable $HTTP_GET_VARS[]. So you’re probably wondering at this point: "So what’s the catch?" Well, there is no catch really, just a few limitations. Since we are invoking the PHP script indirectly and via JavaScript, the final output of the PHP script needs to be valid JavaScript. Think of it as a dynamic .js file, bounded by the same limitations as a regular .js file. A normal PHP script called inside a PHP page can output raw HTML and modify the source code of the page. The JavaScript invoked version obviously cannot, but don’t worry, there’s plenty of what it can do.

Here’s a basic example of a PHP script- ip.php – being called by external JavaScript to do something that JavaScript alone cannot:



//"ip.php" example- display user IP address on any page

Header("content-type: application/x-javascript");


echo "document.write(\"Your IP address is: " . $serverIP . "\")";


And once called by external JavaScript:

<script type="text/javascript" src="ip.php"></script>

Output: Your IP address is:

In the above, we have a normal PHP script that writes out the IP address of the visitor when referenced using external JavaScript, with two important details:

  • A JavaScript header is sent at the very beginning to inform the page that our PHP script is outputting a JavaScript file.
  • Since the final output of our PHP script needs to be a valid .js file, whatever the PHP outputs must conform to valid JavaScript syntax. So to display the IP address from the perspective of JavaScript, the echo function above includes document.write() as part the content to send back to the page.

Notice how I didn’t output the JavaScript script tag itself <script></script>), as just like inside a regular .js file, this isn’t required nor valid.

The ability to reference a PHP script inside your external JavaScript can be very useful! It means your JavaScript now has access to once exclusive information on the server side, whether it’s the server time, the visitor’s IP address, a list of all the files within a certain directory, or mySQL database information. Now even regular HTML pages can utilize this dynamic information, as all they need is a JavaScript on the pages that in turn references the desired PHP script on your server or elsewhere.

Enjoy 😉

how to unmask your passwords securely – JavaScript

Unmasking passwords can remove a lot of frustration when trying to enter long and/or complicated passwords. This simple JavaScript below enables you to do this on any site you are visiting at your discretion.
Remember that doing this will reduce security, for example in an internet cafe where someone could shoulder surf; so use this technique with due diligence and discretion. You have been warned, and I take no responsibility for problems caused by using this script.

var els = document.getElementsByTagName('input');
for(var x = 0; x < els.length; x++) {
if(els[x].type.toLowerCase() == 'password' ) {
var test = els[x].type = 'text';

Simply paste javascript: at the beginning of that, and delete all the newlines so that it becomes a one-liner, then you can delete the text in your browser’s address bar and paste the JavaScript snippet in the address bar instead, then hit Enter. This will cause masked passwords to be revealed.

If you find you will use this a lot, you can bookmark the script. Simply create a bookmark for any page you wish (preferably without an icon), then edit the properties of it so that the URL it points to is the script (ie javascript: var els = document.getElementsByTagName('input'); for(var x = 0; x < els.length; x++) { if(els[x].type.toLowerCase() == 'password' ) { var test = els[x].type = 'text'; }} and rename the bookmark to something common-sense such as “UNMASKER”.

There you have it. [Sourced from techrepublic]