Saturday, December 22, 2012

Getting started with knockout js

Today we will be seeing how to work with knockout js. Objective of this article is to quickly get you up and running with this MVVM framework.

So what is Knockout JS

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

Some key things to understand:
1. observables:  model properties as observables, because these are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies.

2. observable array: If you want to detect and respond to changes on one object, you’d use observables. If you want to detect and respond to changes of a collection of things, use an observableArray

3. computed : these are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change.

For this article we will be creating a view model for simple ma thematic operations like addition, subtraction, multiplication etc...

The code for our view model looks as follows:

function mathematica(){

var self = this;
this.firstNumber = ko.observable(2);
this.secondNumber = ko.observable(3);
//Start off with computed values
this.addition = ko.computed(function(){
var add = this.firstNumber() + this.secondNumber()
return add;
this.substraction = ko.computed(function(){
return this.firstNumber() - this.secondNumber()
this.multiplication = ko.computed(function(){
return this.firstNumber() * this.secondNumber()
this.division = ko.computed(function(){
return this.firstNumber() / this.secondNumber()
this.squareRootFirst = ko.computed(function(){
return Math.sqrt(this.firstNumber())
//Compute the value multiplication table and assign it to the observable array
this.MultiplicationTableGenerate = ko.computed(function(){
var testArray = new Array();
for (var i = 0; i <= 10; i++) {
testArray[i] = i*this.firstNumber();
return testArray;
this.TableValue = ko.observableArray(this.MultiplicationTableGenerate());
this.recalculateTable = function(){
var inputtedNumber = document.getElementById("firstNumber").value;
var newArray = new Array();
for (var i = 0; i <= 10; i++) {
newArray[i] = i*inputtedNumber;
this.setFirstNumber = function() {
var inputtedNumber = document.getElementById("firstNumber").value;
this.setSecondNumber = function() {
var inputtedNumber = document.getElementById("secondNumber").value;

in this code, we first create observables "firstNumber" and "secondNumber". Rest of the variables like addition, subtraction, etc are computed.
In case you’re wondering what the second parameter to ko.computed is (the bit where we passed this in the preceding code), that defines the value of this when evaluating the computed observable. Without passing it in, it would not have been possible to refer to this.firstNumber() or this.secondNumber().

To activate Knockout, add the following line to a 

var instant = new mathematica();

Monday, October 1, 2012

Handling hashChange event

If you intend to build site navigation based on hash values in your URL, one of the major problem you would come across is how to deal with old browsers like IE 7. These old browsers donot support "window.onhashchange".
If you are using jquery then you can initiate the following code if "window.onhashchange" is not detected.

  var url = $(this).attr('href');
  var hashvalue = url.substring(url.indexOf("#")+1,url.length);
  //perform some processing based on this value.

Monday, August 27, 2012

Implementing adaptive ceasar cipher

In this tutorial we will see how to implement ceaser cipher in an adaptive way. Normal ceasar cipher uses a fixed length to shift the characters. Example we shift characters by fixed units example shift by 5 characters or 7 characters. We will make this algorithm adaptive by making this shifting unit variable. This unit can be based on length of the string. Here is how you will do it.

function adaptivecipher(tocipher)
var word_cipher = tocipher;
var word_cipher_length = tocipher.length;
var stepper = word_cipher_length;
var char_library = '0123456789abcdefghijklmnopqrstuvwxyz';
var char_library_length = charset.length;
var cipherText = "";

/*Loop and shift replace the characters*/
var index = word_cipher_length - 1;
for(;index >= 0;index--)
var realchar = word_cipher.charAt(index);
var place_in_char_library = char_library.indexOf(realchar);
if(place_in_char_library != -1)
var newcharposition = place_in_char_library+stepper;
if(newcharposition <= char_library_length)
{cipherText = char_library.charAt(newcharposition) + cipherText;}
{cipherText = char_library.charAt((newcharposition - char_library_length)-1) + cipherText;}
return cipherText;

If we want further make it effective we can shuffle the order in character library.

Sunday, July 1, 2012

Creating a simple contact us form with PHP script

Today we will be building a simple contact us form using PHP. There is not much of description needed for this task

The form












Once this is in place you will need to write the code of PHP which will be as follows

if(isset($_POST['email'])) {
    $email_to = "";
    $email_subject = "Contacted from vergo pharma";
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.


        echo $error."


        echo "Please go back and fix these errors.


    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.

    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.

  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.

  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.

  if(strlen($error_message) > 0) {
    $email_message = "Hi, Someone has contacted you from the website. Details below.\n\n";
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";
    $thankyou = "Thank you ";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers,"-f $email_from");
@mail($email_from, $email_subject, $thankyou); 

This code will work for email accounts (a common problem that mails sent using php scripts are not received at the destination email address which is normally caused in some ISP's and servers that require that the Return-Path header email address match the From email address in order for it to be passed onto the users account.)

Monday, June 4, 2012

Simple email validation using JS

function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if(filter.test(e)){alert("valid email")}
  else{alert("invalid email")}


this code will throw false for any invalid email address. This code checks validity with respect to what is email pattern and what are permissible characters

Wednesday, March 21, 2012

Preventing Caching of AJAX call in jquery

we have been using ajax call for quite a while now, however when used for fetching images or text files we often face cache issue where updated files are not fetched. In order to avoid this issue place following code in first line of your $(document).ready().

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false

Thursday, February 16, 2012

Crunch: The LESS editor and Compiler

A good air app for using less css on windows! Finally we can use less on windows machine without any installation hassles.

Crunch: The LESS editor and Compiler

Crunch it and you're good to go!

Sunday, February 5, 2012

Issue with "ScrollLeft" animation using jquery

In my recent attempt to build a site with horizontal parallax (sites with multiple moving, i came across an issue where my code would only work in chrome but not in other browsers.
After searching on google i came across some articles stating same issue. I was able to resolve it by changing the selector i was using for the animation.
Earlier i was using


I changed it to


and now my code works perfectly fine across all the browsers.