Creating an ON/OFF switch using bootstrap and jQuery

In some projects that I work on, I need a quick way of adding some cool-looking user-friendly on/off switch. Checkboxes are ugly! And I don’t want to add a new component/plugin to the already loaded pages. So, I wrote some quick  code snippet for a switch based on Bootstrap 3 and jQuery. Here is the HTML code:

And here is the jQuery code (should be placed inside any jQuery DOM loaded block):

Here is what the output looks like when the page loads (the default state is locked): jquery-bootstrap-locked-switch

And when the switch is clicked, here is how it looks like (unlocked): jquery-bootstrap-unlocked-switch

Here is a demo of the switch in action. Have fun!

Prepare a LAMP web development server on Amazon EC2

Here is a quick checklist for setting up LAMP development server on Amazon EC2. I used a standard Amazon Linux AMI on a T2.micro instance, which costs about $9/month at the time of writing this.

  1. Edit the DNS zone for your domain to add an A record for a sub-domain to point to the public IP of the instance. I recommend setting the TTL to 60 for fastest updates of IP later if necessary.
  2. Use putty or ssh to log in to the instance.
  3. Follow the instructions at
  4. Test the server by visiting it on your browser using either the public IP or the url.
  5. Prepare web directory: A useful guide for permissions. The Apache user is “apache”, member of group “apache”.
  6. Prepare HTTPS: for Amazon Linux, this is already set up … but for more info, see
  7. Install Codiad (an online code editor/IDE — this enables you to write your code anywhere rather than being bound to your workstation and your desk):
  8. Browse to servername/edit to set up Codiad. Once done, it’s now ready to use. from that same location.

Tip: need to set up multiple virtual hosts on the server? Amazon Linux is based on CentOS. Here is a step-by-step guide on setting up virtual hosts on CentOS. A similar guide for SSL virtual hosts.

How to paginate a database query in PHP — the no-frameworks way

OK, I admit! Every time I have to write similar code I get stuck rethinking it — every time … If I wasted 10 minutes thinking of it every time, and I did so for 100 times, then I’ve already wasted more than 2 working days in the last 12 years doing it! I guess it’s time to stop that loss!

So, the issue I’m talking about is when having a web page (or a web service, or a command line utility, or any other interface) that lists a set of records from a database, and then the user wants to retrieve the next set of records, this is called pagination. If I’m not explaining it clearly, feel free to look it up in Wikipedia.

So, how should pagination be handled in the server side? Here is the most recent way I did it … If you have a better suggestion, feel free to post your comment below. I’ll be using this from now, and update it as necessary:

The tricky part that wastes most of the time in the above code is line 12 .. that is, figuring out the formula for calculating the offset, or the number of records to skip from the query .. it’s a simple one, I know, but if you’re like me and get confused by the zero-one worlds … it could drag your mind for some time! So, I hope this would save you 10 minutes in your next coding adventure.

Making sure a PHP script is accessible only through being included

Let’s say we have a PHP script that we don’t want users to access directly by calling it through their browser. We want that script to be included in other scripts but not accessed by typing its URL.

A lot of sites suggest saving such scripts into a directory outside the document root. This would do, but in some cases might not be an optimal solution. For example, you might need to be able to easily distribute your PHP application in an archive that the user can easily extract into some folder on his site. Telling your users to move some files to a folder outside their web root adds a lot of inconvenience and confusion. And you’ll probably add a lot of support overhead due to this approach.

Another method I prefer is to add code at the top of the script that checks if it is included in another file or being accessed directly. A good way of doing this is using the get_included_files PHP function. Here is what I use at the top of any such scripts:

The first item in the array returned by get_included_files is the path of the script called directly by the user. The following items in the array are any other scripts that were included afterwards. So, the above line of code makes sure the current script is not the first item in that array.

Raspberry PI adventures

I managed finally to have some time to play with the an RPi Model B I received from a friend of mine for experimentation. I prepared all the peripherals as below:


  • An HDMI cable
  • A micro USB 700 mA+ charger (I used my Samsung Galaxy Nexus 1A charger)
  • An Ethernet cable
  • An 8GB class 4 SD card
  • A USB keyboard
  • A USB mouse
  • An LCD TV with HDMI input (not shown above :))

Woo! A long list!

To prepare the OS, I downloaded a Raspbian Wheezy image, a Debian-based distro for RPi. I used Win32DiskImager to dump the image to the SD card. I connected everything, inserted the SD card to the RPi, and powered it on. Within a few moments, I saw a setup screen, where I chose to expand the rootfs to the whole SD card so that it uses all the empty space for storage. I also enabled the SSH server. There was an option to specify the amount of memory reserved for display. I left the default of 64MB for display and 192MB for RAM to run the GUI smoothly, but I’ll probably need to modify this later if I use it as a server.

After that there was a beautiful GUI with some sample applications, including some simple yet enjoyable Python games. The web browser is a basic one and doesn’t run Flash nor HTML5. I didn’t yet try running videos but should do that soon.

I then switched the RPi off, removed all cables except network. Then re-powered it on. I then connected to it via SSH, installed VNC server (via apt-get install tightvncserver). This allowed me to connect remotely to the GUI. I created a script for starting the VNC (~/

I then tried installing a LAMP stack (apache2, mysql-server-5.5, php5, php5-mysql) .. all installed and worked smoothly. The document root is /var/www.

Next things that I plan to check later:

  • Can Firefox or Chrome be installed for a better web experience?
  • Running videos and checking which formats are supported.
  • Using the RPi as a network storage, possibly implementing some RAID via USB for redundancy.
  • Measuring MySQL performance for a possible dedicated database server (though I guess this won’t work due to the very low RAM that comes with RPi).
  • Installing some Podcast subscription software or so for using it as an internet radio.
  • Trying to connect to the internet via a 3G USB modem.
  • Trying to connect a USB webcam.
  • Trying to connect a USB printer (so the RPi becomes a print server).

Related links to check:



Bootstrap theme and IE7 and hours of debugging!

I was trying to apply bootstrap CSS framework to a page and things where going smooth until I started testing it with IE 8. For some reason, the drop-down menu in the navigation bar was not showing correctly .. it was stacked below other elements in the page.

The bootstrap drop-down menu appears correctly in Firefox.
The bootstrap drop-down menu appears correctly in Firefox.


But is rendered incorrectly in IE 8
But is rendered incorrectly in IE 8

Well .. I tried searching for a fix for this issue and stumbled upon several suggestions, mainly involving z-index CSS property. Unfortunately, none of them worked to fix this issue without breaking other elements.

It was really puzzling, specially that the example on the Bootstrap website was working just fine. So, I began tracing its code line by line, trying to remove some of the javascript libraries in my code one by one, adding html5shiv, removing it, adjusting meta tags .. nothing worked.

After several maddening hours, I found the ultimate cause of this issue … it was the Bootstrap theme CSS file that accompanies Bootstrap. This file adds some 3D shading effects to Bootstrap components. Here is how a page looks with and without it.

Bootstrap page without theme file.
Bootstrap page without theme file.
Bootstrap page with theme file.
Bootstrap page with theme file.

In IE 8, the drop-down bug would disappear if the theme file is not loaded.

In IE 8, not loading the Bootstrap theme file would eliminate the drop-down menu bug.
In IE 8, not loading the Bootstrap theme file would eliminate the drop-down menu bug.

So, basically, the fix was to load the Bootstrap theme file only if the browser is not IE, or is IE 9 or higher:

The above code tells browsers that are greater than IE 8 or not IE to load Bootstrap theme file. Otherwise, don’t. This works like a charm, though at the (bearable) cost of sacrificing 3D shading effects for IE 8 and below.

I hope this would help save someone hours of frustration!

Moving from Prototype to jQuery

AppGini used to use Prototype and Scriptaculous javascript framework for client-side scripting. It’s a great framework but it’s not being frequently updated any more, and finding plugins for it is getting harder. So, I decided to move on and migrate to jQuery. jQuery is in very active development, has a huge user base, has a huge library of actively-developed plugins, and is used by many great client-side frameworks, like bootstrap for example.

During the migration, I created a checklist of code lines I needed to change. I thought this would be useful for anyone who wishes to follow this path. Feel free to add your own points in the comments.

Prototype code To convert to jQuery, replace with
document.observe("dom:loaded", function(){ some_code }); jQuery(function(){ some_code });
$$(selector)[x] jQuery(selector).eq(x)
$('id') jQuery('#id')
.style.x = 'y' .css({ x: 'y' })
.checked .prop('checked')
.disabled .prop('disabled')
.some_attr .attr('some_attr')
.value = x .val(x)
.observe('event', function(){}) .event(function(){})
$F('id') $('#id').val()
.fade({duration: x}) .fadeOut(x * 1000)
.appear({duration: x}) .fadeIn(x * 1000)
Effect.Appear fadeIn()
Effect.Fade fadeOut()
.update('new content') .html('new content')

Tip: To work directly with DOM methods after selecting an element through a jQuery selector, use get(0) or [0] .. for example:

// or