November 24

Cancel $http requests in AngularJS

Recently i came across a situation where i needed to cancel $http requests in Angular. At first glance at the issue, i thought i did not have control over the requests that are sent, however after some research came to the conclusion that we can cancel $http requests. The following is what i did:

Example 1 – Normal jQuery – Ajax

Keep a reference to the request as follows:

var xhr = $.ajax({
    type: "POST",
    url: "user.php",
    data: "fname=Roy&lname=MJ",
    success: function(result) {
        alert("Success: " + result);
    },
    error: function(err) {
        alert("Error: " + err);
    }
});

Now you can simple cancel $http requests as follows:

//kill the request
xhr.abort()

In AngularJS, the basic idea is similar, but with the help of promises, we can implement as:

var canceller = $q.defer();
$http.get("/users.php", {
        timeout: canceller.promise
    })
    .then(function(response) {
        $scope.movie = response.data;
    });
$scope.cancel = function() {
    canceller.resolve("user cancelled");
};

Cheers

August 12

Basic git commands

Here is a list of some basic Git commands that will help you get started with git.

Checkout a new branch

git clone git-repo-url
eg:-
git clone https://github.com/roymj88/git-helper.git

Create a new local repository

git init

Create a new branch from current working branch and switch to it

git checkout -b <new-branch-name>

Switch to a new branch

git branch <branch-name>

List all available branches

git branch

Check status of files

git status

Add files for commit

git add <file-name>
OR
git add <file-name-1> <file-name-2> <file-name3>
OR
git add *

Remove files for commit

git rm <file-name>

Commit

git commit -m "Message for commit"

Pull – Update local repo with latest update from server

git pull

Push – Update changes to repository

git push origin master
#Updates 'master' branch
git push origin <branch-name>
#Updates corresponding branch

Stash – Store changes without commiting

git stash

Stash Apply – Apply stashed changes

git stash apply

Merge

git merge <branch-name>
#Merges a different branch into your active branch

View more at : https://github.com/roymj88/git-commands-helper

Category: Git | LEAVE A COMMENT
July 9

How to Configure E-tags

The E-Tag or entity tag is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for web cache validation, and which allows a client to make conditional requests. This allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed. E-Tag can also be used for optimistic concurrency control,[1] as a way to help prevent simultaneous updates of a resource from overwriting each other. (Wiki)

We can set the E-Tag by adding the following lines in your htaccess file.

Header unset Pragma
Header unset ETag
FileETag None
July 9

How To Install phpMyAdmin on Ubuntu 14.04

Introduction

While many users need the functionality of a database management system like MySQL, they may not feel comfortable interacting with the system solely from the MySQL prompt.

phpMyAdmin was created so that users can interact with MySQL through a web interface. In this guide, we’ll discuss how to install and secure phpMyAdmin so that you can safely use it to manage your databases on Ubuntu 14.04.

Prerequisites

Before you get started with this guide, you need to have some basic steps completed.

First, we’ll assume that you are using a non-root user with sudo privileges, as described in steps 1-4 in the initial server setup of Ubuntu 14.04.

We’re also going to assume that you’ve completed a LAMP (Linux, Apache, MySQL, and PHP) installation on your Ubuntu 14.04 server. If this is not completed yet, you can follow this guide on installing a LAMP stack on Ubuntu 14.04.

Once you are finished with these steps, you’re ready to get started with this guide.

Install phpMyAdmin

To get started, we can simply install phpMyAdmin from the default Ubuntu repositories. We can do this by updating our local package index and then using the apt packaging system to pull down the files and install them on our system:

sudo apt-get update
sudo apt-get install phpmyadmin

This will ask you a few questions in order to configure your installation correctly.

For the server selection, choose apache2. Note: If you do not hit “SPACE” to select Apache, the installer will not move the necessary files during installation. Hit “SPACE”, “TAB”, and then “ENTER” to select Apache.

Select yes when asked whether to use dbconfig-common to set up the database. You will be prompted for your database administrator’s password. You will then be asked to choose and confirm a password for the phpMyAdmin application itself. The installation process actually adds the phpMyAdmin Apache configuration file into the /etc/apache2/conf-enabled/ directory, where it is automatically read.

The only thing we need to do is explicitly enable the php5-mcrypt extension, which we can do by typing:

sudo php5enmod mcrypt

Afterwards, you’ll need to restart Apache for your changes to be recognized:

sudo service apache2 restart

You can now access the web interface by visiting your server’s domain name or public IP address followed by /phpmyadmin:

http://domain_name_or_IP/phpmyadmin

phpmyadmin

phpmyadmin

You can now log into the interface using the root username and the administrative password you set up during the MySQL installation.

Category: MySQL, PHP | LEAVE A COMMENT
July 9

Introduction to HTML5 Canvas

HTML5 Canvas element offers a wide range of features which were once possible only with the help Flash and Action Scripting. Using HTML5 canvas, we can render 2-D and 3-D animations on a html page. While 2-D is quite popular now and most browsers support this, 3-D is yet to become a major buzz. But soon it ought to be the way ahead for browser based animations(CSS3 would be another option, but its nowhere near to canvas).

Advantages of using HTML5 Canvas tag

  • Dynamic graphics
  • Online and Offline games
  • Animations
  • Interactive Video & Audio

Dis-advantages of using HTML5 Canvas tag

Canvas is a really cool technology, but it has 3 significant concerns/challenges (not necessarily in order)

  • Its text support is very newish so getting a font onto a canvas only works in the latest stuff (in other cases you need HTML/CSS overlays) or nasty hacks to draw the letter forms onto the canvas.
  • Interactivity is a hack and half. If you want to make a canvas drawing clickable you are forced to use an overlaid image maps or div tags or do some nutty pixel map catching events and figuring out what pixels they hit. A canvas image is a rendered bit map and really not meant to be interacted with how many people want.
  • No native IE support. Sorry that translation library doesn’t cut performance wise it for anything significant and clearly IE is still a browser force whether you like it or not.

Browser Support

IE FireFox Safari Chrome Opera iPhone Android
7.0 + * 3.0 + 3.0 + 3.0 + 10.0 + 1.0 + 1.0 +

* Internet Explorer 7 and 8 require the third-party explorercanvas library. Internet Explorer 9 supports canvas natively.

Following is a simple example to give an insight about using canvas.

Step 1

Add canvas to the html DOM

    <canvas height="300" width="500" id="canvas"></canvas>
Step 2

Adding color fill to the canvas using canvas properties using javascript.

		var canvas 		= document.getElementById("canvas");
		var c 			= canvas.getContext("2d");
		c.fillStyle 		= "Red";
		c.fillRect(10, 10, 400, 250); // X-Axis, Y-Axis, Width, Height
Step 3

Run the page in a browser and you will get something like this :

canvas

More to follow in coming posts regarding canvas. Thanks for reading. Cheers!

May 15

Enable g-zip compression

G-zip is a software application used for file compression and decompression. The program was created by Jean-Loup Gailly and Mark Adler as a free software replacement for the compress program used in early Unix systems, and intended for use by the GNU Project (the “g” is from “GNU”).

G- zip Compression

G- zip Compression

The following code can be used to enable g-zip compression on your hosting.

In your .htaccess file, add the following :

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

You can confirm the same by checking in Gtmetrix(http://gtmetrix.com) which is an amazing tool to check the website performance.

If the above code doesn’t work, try the following :

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

Hope this helps!

May 15

An interesting read based on a mail sent by an IITian to Rahul Gandhi

THE CURIOUS CASE OF RAHUL GANDHI

Rahul Gandhi: “I feel ashamed to call myself an INDIAN after seeing what
has happened here in UP”.

PLEASE DON’T BE ASHAMED OF U.P… YET

Please don’t be ashamed of Uttar Pradesh yet. Congress ruled the State
for the Majority of the duration Pre Independence to Post Independence..
from 1939 to 1989 ( barring the Periods of Emergency.. Thanks to your
Grand Mom Indira G. and a couple of transitional Governments)

8 out of the total 14 Prime Ministers of India have been from UP, 6 out
of those 8 have been from Congress…

I think your party had more than half a century and half a Dozen PM’s to
build a State…

The Reason Mulayam Singh, subsequently came to Power is because your
party wasn’t exactly Gandhian in their dealings in the State.. So May be
If you look at in totality the present chaos in UP is the outcome of the
glorious leadership displayed by Congress in UP for about 50 years!

So Please don’t feel ashamed as yet Dear Rahul.. For Mayawati is only
using the Land Acquisition Bill which your party had itself used to LOOT
the Farmers many times in the Past!

WHY DIDN’T YOUR PARTY CHANGE THE BILL WHEN IT WAS IN POWER FOR SO LONG?

Not that I Endorse what Mayawati is doing.. What Mayawati is doing is
Unacceptable..

But the past actions of your party and your recent comments, puts a
question mark on your INTENT and CONSISTENCY.

YOU REALLY WANT TO FEEL ASHAMED

But don’t be disappointed, I would give you ample reasons to feel
ashamed…

You really want to feel Ashamed..?

First Ask Pranav Mukherjee, Why isn’t he giving the details of the
account holders in the Swiss Banks.

Ask your Mother, Who is impeding the Investigation against Hasan Ali?

Ask her, Who got 60% Kickbacks in the 2G Scam ?

Kalamdi is accused of a Few hundred Crores, Who Pocketed the Rest in the
Common Wealth Games?

Ask Praful Patel what he did to the Indian Airlines? Why did Air India
let go of the Profitable Routes ?

Why should the Tax Payer pay for the Air India losses, when you intend
to eventually DIVEST IT ANYWAY!!!

Also, You People can’t run an Airline Properly. How can we expect you to
run the Nation?

Ask Manmohan Singh. Why/What kept him quiet for so long?

Are Kalmadi and A Raja are Scapegoats to save Big Names like Harshad
Mehta was in the 1992 Stock Market Scandal ?

Who let the BHOPAL GAS TRAGEDY Accused go Scot Free? ( 20,000 People
died in that Tragedy)

Who ordered the State Sponsored Massacre of SIKHS in 84?

Please read more about, How Indira Gandhi pushed the Nation Under
Emergency in 76-77, after the HC declared her election to Lok Sabha
Void!

(I bet She had utmost respect for DEMOCRACY and JUDICIARY and FREE
PRESS)

I guess you know the answers already. So My question is, Why the Double
Standards in Judging Mayawati and members of your Family and Party?

I condemn Mayawati. But Is She the only one you feel Ashamed for?

What about the ones close to you? For their contribution to the Nation’s
Misery is beyond comparison.

You talk about the Land being taken away from the Farmers. How many
Suicides have happened under your Parties Rule in Vidarbha ? Does that
Not Ashame You ?


THE 72,000 CRORE LOAN WAIVER

Your Party gave those Farmers a 72,000 Crore Loan Waiver. Which didn’t
even reach the Farmers by the way.

So, Why don’t you focus on implementing the policies which your govt.
has undertaken, instead of earning brownie points by trying to
manufacture consent by bombarding us with pictures of having food with
Poor Villagers….

You want to feel ashamed. You can feel ashamed for your Party taking
CREDIT for DEBITING the Public Money (72,000 crores) from the Government
Coffers and literally Wasting it…

You want to feel ashamed.. Feel ashamed for that…

WHY ONLY HIGHLIGHT THIS ARREST?

Dear Rahul, to refresh your memory, you were arrested/detained by the
FBI the BOSTON Airport in September 2001.

You were carrying with you $ 1,60,000 in Cash. You couldn’t explain why
you were carrying so much Cash.

Incidentally He was with his Columbian girlfriend Veronique Cartelli,
ALLEGEDLY, the Daughter of Drug Mafia.
9 HOURS he was kept at the Airport.
Later then freed on the intervention of the then Prime Minister
Mr.Vajpayee.. FBI filed an equivalent of an FIR in US and released him.

When FBI was asked to divulge the information, by Right/Freedom to
Information Activists about the reasons Rahul was arrested … FBI asked
for a NO OBJECTION CERTIFICATE from Rahul Gandhi.
So Subramaniyam Swami wrote a Letter to Rahul Gandhi, ” If you have
NOTHING to HIDE, Give us the Permission”
HE NEVER REPLIED!

Why did that arrest not make Headlines Rahul? You could have gone to the
Media and told, “I am ashamed to call myself an INDIAN?”.

Or is it that, you only do like to highlight Symbolic Arrests (like in
UP) and not Actual Arrests ( In BOSTON)

Kindly Clarify…..

In any case, you want to feel ashamed, Read Along…

YOUR MOTHER’S SO CALLED SACRIFICE OF GIVING UP PRIME MINISTER SHIP in
2004.

According to a Provision in the Citizenship Act.

A Foreign National who becomes a Citizen of India, is bounded by the
same restrictions, which an Indian would face, If he/she were to become
a Citizen of Italy.

(Condition based on principle of reciprocity)

[READ ANNEXURE- 1&2]

Now Since you can’t become a PM in Italy, Unless you are born there.

Likewise an Italian Citizen can’t become Indian PM, unless He/She is not
born here!

Dr. SUBRAMANIYAM SWAMI (The Man who Exposed the 2G Scam) sent a letter
to the PRESIDENT OF INDIA bringing the same to his Notice. [READ LETTER
TO THE PRESIDENT IN ANNEXURE -3]

PRESIDENT OF INDIA sent a letter to Sonia Gandhi to this effect, 3:30
PM, May 17th, 2004.

Swearing Ceremony was scheduled for 5 PM the same Day.

Manmohan Singh was brought in the Picture at the last moment to Save
Face!!

Rest of the SACRIFICE DRAMA which she choreographed was an EYE WASH!!!

Infact Sonia Gandhi had sent, 340 letters, each signed by different MP
to the PRESIDENT KALAM, supporting her candidacy for PM.

One of those letters read, I Sonia Gandhi, elected Member from Rai
Bareli, hereby propose Sonia Gandhi as Prime Minister.

So SHE was Pretty INTERESTED! Until She came to know the Facts!
So She didn’t make any Sacrifice, It so happens that SONIA GANDHI
couldn’t have become the PM of INDIA that time.

You could be Ashamed about that Dear Rahul!! One Credential Sonia G had,
Even that was a HOAX!

THINK ABOUT YOURSELF.

You go to Harvard on Donation Quota. ( Hindujas Gave HARVARD 11 million
dollars the same year, when Rajiv Gandhi was in Power)

Then you are expelled in 3 Months/ You Dropped out in 3 Months…. (
Sadly Manmohan Singh wasn’t the Dean of Harvard that time, else you
might have had a chance… Too Bad, there is only one Manmohan Singh!)

Some Accounts say, You had to Drop out because of Rajiv Gandhi’s
Assassination.

May be, But Then Why did you go about lying about being Masters in
Economics from Harvard .. before finally taking it off your Resume upon
questioning by Dr. SUBRAMANIYAM SWAMI (The Gentlemen who exposed the 2G
Scam)

At St. Stephens.. You Fail the Hindi Exam.

Hindi Exam!!!

And you are representing the Biggest Hindi Speaking State of the
Country?

SONIA GANDHI’s EDUCATIONAL QUALIFICATIONS

Sonia G gave a sworn affidavit as a Candidate that She Studied English
at University of Cambridge

[SEE ANNEXURE-6, 7_37a]

According to Cambridge University, there is no such Student EVER! [ SEE
ANNEXURE -7_39]

Upon a Case by Dr. Subramaniyam Swami filed against her,

She subsequently dropped the CAMBRIDGE CREDENTIAL from her Affidavit.

Sonia Gandhi didn’t even pass High School. She is just 5th class Pass!

In this sense, She shares a common Educational Background with her 2G
Partner in Crime, Karunanidhi.

You Fake your Educational Degree, Your Mother Fakes her Educational
Degree.

And then you go out saying, ” We want Educated Youth into Politics!”

Letters sent by Dr. Swami to EC and then Speaker of Lok Sabha are in
ANNEXURE 7_36 &7_35 RESPECTIVELY

Contrast that with Gandhi Ji , who went to South Africa, Became a
Barrister, on Merit, Left all that to work for South Africa, then for
the Country….

WHY LIE ABOUT EDUCATIONAL CREDENTIALS?

Not that Education is a Prerequisite for being a great Leader, but then
you shouldn’t have lied about your qualifications!

You could feel a little ashamed about Lying about your Educational
Qualifications. You had your reasons I know, Because in India, WE
RESPECT EDUCATION!

But who cares about Education, When you are a Youth Icon!!

YOUTH ICON

You traveled in the Local Train for the first time at the Age of 38.

You went to some Villages as a part of Election Campaign.

And You won a Youth Icon!! … That’s why You are my Youth Icon.

For 25 Million People travel by Train Everyday. You are the First Person
to win a Youth Icon for boarding a Train.

Thousands of Postmen go to remotest of Villages. None of them have yet
gotten a Youth Icon.

You were neither YOUNG Nor ICONIC!

Still You became a Youth Icon beating Iconic and Younger Contenders like
RAHUL DRAVID.

Shakespeare said, What’s in a Name?

Little did he knew, It’s all in the Name, Especially the Surname!

Speaking of Surname, Sir

DO YOU REALLY RESPECT GANDHI, OR IS IT JUST TO CASH IN ON THE GOODWILL
OF MAHATMA?

Because the Name on your Passport is RAUL VINCI.

Not RAHUL GANDHI..

May be if you wrote your Surname as Gandhi, you would have experienced,
what Gandhi feels like, LITERALLY ( Pun Intended)

You People don’t seem to use Gandhi much, except when you are fighting
Elections. ( There it makes complete sense).

Imagine fighting elections by the Name Raul Vinci…

It feels sadly Ironic, Gandhi Ji, who inspired Icons like Nelson Mandela
,Martin Luther King Jr. and John Lennon, across the world, Couldn’t
inspire members of his party/ Nehru’s Family, who only seem to use his
Surname for the purposes of FIGHTING ELECTIONS and conveniently use a
different name on their PASSPORT.

You use the name GANDHI at will and then say, ” Mujhe yeh YUVRAJ shabd
Insulting lagta hai! Kyonki aaj Hindustan mein Democracy hai, aur is
shabd ka koi matlab nahin hai!

YUVRAJ, Itna hi Insulting lagta hai, to lad lo RAUL VINCI ke Naam se!!!
Jin Kisano ke saath photo khinchate ho woh bhi isliye entertain karte
hain ki GANDHI ho.. RAUL VINCI bol ke Jao… Ghar mein nahin
ghusaenge!!!

You could feel ashamed for your Double Standards.

YOUTH INTO POLITICS.

Now You want Youth to Join Politics.

I say First you Join Politics.

Because you haven’t Joined Politics. You have Joined a Family Business.

First you Join Politics. Win an Election fighting as RAUL VINCI and Not
Rahul Gandhi, then come and ask the youth and the Educated Brass for
more involvement in Politics.

Also till then, Please don’t give me examples of Sachin Pilot and Milind
Deora and Naveen Jindal as youth who have joined Politics..

They are not Politicians. They Just happen to be Politicians.

Much Like Abhishek Bachchan and other Star Sons are not Actors. They
just happen to be Actors (For Obvious Reasons)

So, We would appreciate if you stop requesting the Youth to Join
Politics till you establish your credentials…

WHY WE CAN’T JOIN POLITICS!

Rahul Baba, Please understand, Your Father had a lot of money in your
Family account ( in Swiss Bank) when he died.

Ordinary Youth has to WORK FOR A LIVING.

YOUR FAMILY just needs to NETWORK FOR A LIVING

If our Father had left thousands of Crores with us, We might consider
doing the same..

But we have to Work. Not just for ourselves. But also for you. So that
we can pay 30% of our Income to the Govt. which can then be channelized
to the Swiss Banks and your Personal Accounts under some Pseudo Names.

So Rahul, Please don’t mind If the Youth doesn’t Join Politics. We are
doing our best to fund your Election Campaigns and your Chopper Trips to
the Villages.

Somebody has to Earn the Money that Politicians Feed On.

NO WONDER YOU ARE NOT GANDHI’S. YOU ARE SO CALLED GANDHI’S!!

Air India, KG Gas Division, 2G, CWG, SWISS BANK Account Details… Hasan
Ali, KGB., FBI Arrest..

You want to feel ashamed..

Feel Ashamed for what the First Family of Politics has been reduced
to…

A Money Laundering Enterprise.

NO WONDER YOU ARE NOT GANDHI’S BY BLOOD. GANDHI is an adopted Name. For
Indira didn’t marry Mahatma Gandhi’s Son.

For even if you had one GENE OF GANDHI JI in your DNA. YOU WOULDN’T HAVE
BEEN PLAGUED BY SUCH ‘POVERTY OF AMBITION’ ( Ambition of only EARNING
MONEY)

You really want to feel Ashamed.

Feel Ashamed for what you ‘ SO CALLED GANDHI’S’ have done to MAHATMA’S
Legacy..

I so wish GANDHI JI had Copyrighted his Name!

Meanwhile, I would request Sonia Gandhi to change her name to $ONIA
GANDHI, and you could replace the ‘R’ in RAHUL/RAUL by the New Rupee
Symbol!!!

RAUL VINCI : I am ashamed to call myself an Indian.

Even we are ashamed to call you so!

P.S: Popular Media is either bought or blackmailed, controlled to
Manufacture Consent!

My Guess is Social Media is still a Democratic Platform. (Now they are
trying to put legislations to censor that too!!)

Meanwhile, Let’s ask these questions, for we deserve some Answers.

For we are all Gandhi’s. For Bapu is the Father of the Nation!

To know more, Try looking for Dr. SUBRAMANIYAM SWAMI. He is the reason
today 2G SCAM is being Investigated!!!

YOURS SINCERELY

NITIN GUPTA ( RIVALDO)

B.Tech, IIT Bombay

May 6

Load all images from a folder into web page using Jquery/Javascript

The following source code can be used to load all images from a folder into webpage :

var dir = "src/themes/base/images/";
var fileextension = ".png";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //Lsit all png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http:///", "");
            $("body").append($("<img src=" + dir + filename + "></img>"));
        });
    }
});

Hope this helps. The above is actually a good answer provided in SO and i’m adding the link also here.

URL : http://stackoverflow.com/questions/18480550/how-to-load-all-the-images-from-one-of-my-folder-into-my-web-page-using-jquery/18480589#18480589

April 2

TP – Version 2.0

Following up regarding the warm welcome that was given to the Version 1(http://www.change.org/en-IN/petitions/technopark-management-team-withdraw-the-new-unilateral-decision-to-impose-car-parking-fee-for-open-space-parking-inside-technopark-trivandrum-campus), TP management has come forward with further suggestions to improve the financial capability of TP(TP is literally running at loss as per TP governing body).

Lift

Pay Rs 10/- for every-time you use lift. It is advised to hop on each others shoulder so that only two feet touches the ground. This is done to increase lift-pooling.

Toilet/Rest-room

Pay Rs 10 and Rs 50 according to your need. Here also it is adviced that multiple people use the same space at a given time to save electricity, water and maintenance cost.

Walking

Pay Rs 100 monthly charge for using the roads inside TP. Using shoes/sandals on roads/concrete tends to wear down the roads and cause heavy maintenance. You cannot walk-pool here,but there is a discount if one person is carrying another one and walking. You only need to pay Rs 50.

Veranda inside Buildings

Since this is not part of any firm and is a facility provided by TP, Rs 5 will be charged per day for using Veranda of any floor.

Note : You would need to pay for each floor that you are stepping on.

Mobile Phones

Much thought was given into this by the TP authoriy especially MD. Even though mobile towers are not provided by TP, the range however comes within the vicinity of TP and hence they have concluded that it can be charged as well. Rates are however as follows:

Miss Call – Rs 1 per miss call

Message – Rs 5 per msg

Call – Rs 10 per minute

Internet – Rs 15 per 1kb

Note : Different packages are available for eg: If you purchase a package for Rs 50, you will get 30 miss calls, 10 messages, 5 calls and 5 kb internet.

More plans are in place for further increasing the “pooling” mentality and also to cut down on the additional expense levied by TP employees on ‘poor’ TP.

P.S: The above details are completely fiction and not aimed at defaming anyone.

Category: Fun, Humour | 6 Comments
January 16

Ping to google, bing & yandex

While trying to do SEO for your website, pinging the sitemap to the search engines become very vital. This will ensure that the new links are crawled by the search engines and much faster than how it gets crawled normally.

SEO

SEO

You need to make sure that you follow these while creating your sitemap :

  • Sitemap should be in valid xml format.
  • Sitemap should not contain any broken links.
  • Better to have latest sitemap pinged rather than old one.

Google

Add your website sitemap path at the end of following link :

http://www.google.com/webmasters/tools/ping?sitemap=yoursitemap.xml

For eg :

http://www.google.com/webmasters/tools/ping?sitemap=http://blog.roymj.co.in/sitemap.xml

gives :
http://www.google.com/webmasters/tools/ping?sitemap=http://blog.roymj.co.in/sitemap.xml

Bing

Add your website sitemap path at the end of following link :

http://www.bing.com/webmaster/ping.aspx?siteMap=yoursitemap.xml

For eg :

http://www.bing.com/webmaster/ping.aspx?siteMap=http://blog.roymj.co.in/sitemap.xml

gives :
http://www.bing.com/webmaster/ping.aspx?siteMap=http://blog.roymj.co.in/sitemap.xml

Yandex

Add your website sitemap path at the end of following link :

http://blogs.yandex.ru/pings/?status=success&url=yoursitemap.xml

For eg :

http://blogs.yandex.ru/pings/?status=success&url=http://blog.roymj.co.in/sitemap.xml

gives :
http://blogs.yandex.ru/pings/?status=success&url=http://blog.roymj.co.in/sitemap.xml

Thats all that is needed to ping your website to search engines and you can see your links being crawled by these search engines very soon. Thank you for reading and do leave comments or questions regarding the same.

Category: SEO | 3 Comments
January 8

Prevent jQuery events from firing multiple times

Everyone who are using jQuery will know that sometimes the jQuery events(click, bind, live, on etc ) may fire more than once due to event bubbling.

jquery-events

jquery-events

For example, consider the following code snippet :

$(document).on("click", ".button", function (e) {
    alert("Clicked");
});

Due to event bubbling, a single click on the .button can trigger the click function multiple times. A detailed explanation regarding Event Bubbling and Capturing is provided on the link.

The above problem can be easily resolved by handling the event as follows :

$(document).on("click", ".button", function (e) {
    e.preventDefault();
    if (e.handled !== true) { //Checking for the event whether it has occurred or not.
        e.handled = true; // Basically setting value that the current event has occurred.
        alert("Clicked");
    }
});

However the above solution wont stop event binding process, it will just prevent multiple jQuery events from executing.

Cheers.

December 24

20 Javascript Tips and Tricks

Following contains a list of javascript snippets which can be included in our projects. Ive been collecting this locally like a library which helped me through my projects. Now just thought of sharing it over here.
Javascript

1) How to get query string values in JavaScript ?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
    results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

2) How to redirect page in JavaScript ?

// similar behavior as an HTTP redirect
window.location.replace("http://blog.roymj.co.in");
// similar behavior as clicking on a link
window.location.href = "http://blog.roymj.co.in";

3) How to get a timestamp in JavaScript ?

var currentTimeStamp = new Date().getTime();

4) Check if one string contains another substring in JavaScript ?

indexOf returns the position of the string in the other string. If not found, it will return -1.

var s = "foo";
alert(s.indexOf("oo") != -1);

5) How to Capture the close Event of a Browser ?

JS :

function PageUnloadHandler() {
    alert("Do something to invalidate the sessions");
}

HTML :

<body onbeforeunload="PageUnloadHandler()">
    <!-- Body content -->
</body>

6) How to use the Conditional Operator in JavaScript ?
Instead of using the following :

if (val) {
  return foo();
} else {
  return bar();
}

We can simply use :

return val ? foo() : bar();

7) How to remove a property from a JavaScript object ?

var myJSONObject = {
    "fn": "Roy",
    "ln": "MJ",
    "loc": "India"
};
//To remove propery loc
delete myJSONObject.loc;
// or,
delete myJSONObject['loc'];

8) How to detect an undefined object property in JavaScript ?

var something = myJSONObject.fakeObject;
if (typeof something === "undefined") {
    alert("something is undefined");
}

9) How to Validate Email address in JavaScript ?

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

10) How do I append to an array in JavaScript ?

// initialize array
var arr = [
    "Test 1",
    "Test 2",
    "Test 3"
];
// append new value to the array
arr.push("Test 4");

11) How to check for an empty string in JavaScript ?

if (strValue) {
    //do something
}else{
    //do something
}

12) How to convert a JavaScript string value to all lower case letters ?

var str = "Your Name";
str.toLowerCase();//returns "your name"

13) How to clear an array in JavaScript ?

A = [1,2,3,4];

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;

14) How to remove specific element from an array in JavaScript ?

First, find the index of the element you want to remove :

var array = [2, 5, 9];
var index = array.indexOf(5);

Then remove it with splice :

if (index > -1) {
    array.splice(index, 1);
}

15) How to get the selected value of dropdownlist using JavaScript?

If you have a select element that looks like this :

<select id="test">
    <option value="1">Test 1</option>
    <option value="2" selected="selected">Test 2</option>
    <option value="3">Test 3</option>
</select>

Then the following code will fetch corresponding values of selected item from the select box

var selected      = document.getElementById("test");
var selectedValue = selected.options[selected.selectedIndex].value;
var selectedText  = selected.options[selected.selectedIndex].text;

16) How to shuffle an array in JavaScript?

var list = [1,2,3,4,5,6,7,8,9];
list = list.sort(function() Math.random() - 0.5);
print(list); // prints something like: 4,3,1,2,9,5,6,7,8

17) How to add break-point programmatically in JavaScript?

// ...
debugger;
// ...

If a debugger is present or active, it will cause it to break immediately, right on that line.

Otherwise, if the debugger is not present or active this statement has no observable effect.

18) How to insert an array into another array in JavaScript?

var a = [1,2,3,7,8,9];
var b = [4,5,6];
var insertIndex = 3;
a.splice.apply(a, Array.concat(insertIndex, 0, b));
print(a); // prints: 1,2,3,4,5,6,7,8,9

19) How can you check for a #hash in a URL using JavaScript?

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}

20) How can you get the height and width of a rendered image using JavaScript?

var image  = document.getElementById('image');
var width  = image.clientWidth;
var height = image.clientHeight;

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

December 20

Render templates in backbone using underscore.js

There are many ways to render html templates dynamically in a Backbone.js application and using Underscore.js is one of the simplest and best one. Full details are explained here. I have not gone into the depth of routers/models/view, but just providing a detailed explanation of this particular method.

Using Backbone and Underscore :

Backbone.js & Underscore.js

Folder Structure

The folder Structure can be as follows :

Root:
 ├───css
 ├───js
 │   ├───router.js
 │   ├───model.js
 │   ├───view.js
 │   └───config.js
 ├───templates
 │   ├───home.html
 │   ├───login.html
 │   └───register.html
 └───images
 └───index.html

Base Template

You will need to have a base template(index.html) within which you will be rendering the different templates. This will ensure that common html contents like hearder, footer, navigation menus etc are not loaded everytime a new page is rendered and thereby increasing the page loading speed drastically.

Sample structure can be as follows :

<html>
<head>
<!--Relevant CSS files-->
</head>
<body>
<div>
<div>
<!--HTML content for header-->
</div>
<div id="template">
<!--This would be where the dynamic content will be loaded-->
</div>
<div>
<!--HTML content for footer-->
</div>
</div>
<!--Include relevant JS Files-->
</body>
</html>

Note : Please note that you can decide on the structure of template as one wants. What i am using is a more general one so that everyone could relate to it easily.

———-

View

In your view, you can render a particular template to the base template as follows :

var LoginView = Backbone.View.extend({
el: "#template", //Container div inside which we would be dynamically loading the templates
initialize: function () {
console.log('Login View Initialized');
},
render: function () {
var that = this;</div>
<div>
//Fetching the template contents
$.get('templates/login.html', function (data) {
template = _.template(data, {}); //Option to pass any dynamic values to template
that.$el.html(template); //adding the template content to the main template.
}, 'html');</div>
<div>
}
});
var loginView = new LoginView();</div>
<div>

Note that the `el` tag is very important.

To pass values to view, simply pass it like :

var data_to_passed = "Hello";
$.get('templates/login.html', function (data) {
template = _.template(data, {
data_to_passed: data_to_passed
}); //Option to pass any dynamic values to template
that.$el.html(template); //adding the template content to the main template.
}, 'html');

And in the template :

<%=data_to_passed;>//Results in "Hello"

You can pass an array, object or even a variable.

Hope this has been helpful. Cheers

December 18

Best JavaScript Frameworks

The period 2012-2013 has seen a major surge in HTML5 Technologies especially the JS Frameworks. All of these can be categorized into MV* patterns. The reason for the sudden rise in popularity for JS frameworks largely goes to the fact that numerous smart-phones are now available with literally any resolution and sizes and websites and applications are forced to adapt quickly or fall apart. As the User Experience plays an important role than ever before, one page websites became the future replacing PHP powered websites to use PHP just for back-end purpose.

What Is MVC, Or Rather MV*?

These modern frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC (Model-View-Controller). MVC separates the concerns in an application down into three parts:

  • Models represent the domain-specific knowledge and data in an application. Think of this as being a ‘type’ of data you can model — like a User, Photo or Note. Models should notify anyone observing them about their current state (e.g Views).
  • Views are typically considered the User-interface in an application (e.g your markup and templates), but don’t have to be. They should know about the existence of Models in order to observe them, but don’t directly communicate with them.
  • Controllers handle the input (e.g clicks, user actions) in an application and Views can be considered as handling the output. When a Controller updates the state of a model (such as editing the caption on a Photo), it doesn’t directly tell the View. This is what the observing nature of the View and Model relationship is for.

MV*-architecture is not a kind of fashion, or killer-feature, or something that could be thrown out. It is a pragmatical way to organize rich UI-applications to tackle complexity of the modern programs.

Why use Modular Pattern?

  1. Not everyone structures code by default. Frameworks enforce structure to some extent. This extent is variable based on how much scaffolding they provide. Too much scaffolding usually translates to steeper learning curve.
  2. Frameworks generally encapsulate design/programming patterns from the collective experience of a larger community, so in some cases there will already be structure in there, while you will build and re-factor.
  3. Mostly developers will come and go, using popular/standard frameworks makes it easier for developers other than the original developer to understand the structure. Good frameworks are well documented and have active communities to be able to ask for help.
  4. As you move from project, you most likely copy/paste code from previous project that you now require in a new project. In case you use a framework even if its your own MV* framework, you just import and include this framework each time.

Possible Disadvantages

  • It tends to be heavy weight for implementing. Where you could have gotten away with 1 class, you’ll now have three. On smaller projects, you’re right to question the benefits of MVC.
  • It can be frustrating to stay within the structure of MVC. There’s always the temptation to let Controller code bleed into the View, or let the View directly access the Model. After you write your umpteenth wrapper function, you’ll wonder why you’re doing it.
  • MVC presumes your app will live forever and will change technologies. If you never change the UI, the data source, or the business logic then you kind of wasted your time in encapsulating those layers in anticipation of change.

Framework or just a Library?

Before you pick to work on a particular JavaScript Framework or a Library, it’s important to understand the difference between the two. Libraries just fit into your existing architecture and add a specific functionality whereas a Framework gives you an architecture and you will need to follow the rules. To make it simpler for you – Backbone.js and Knockout.js are JavaScript libraries and Ember.js and Angular.js are frameworks. Lets discuss briefly about each one of them.

Angular.js

AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier.

The Key components for an Angular.js powered application will be :

  • Template : An Angular template is the declarative specification that, along with information from the model and controller, becomes the rendered view that a user sees in the browser. It is the static DOM, containing HTML, CSS, and angular-specific elements and angular-specific element attributes. The Angular elements and attributes direct angular to add behavior and transform the template DOM into the dynamic view DOM.
  • Directives : At a high level, directives are markers on a DOM element (such as an attribute, element name, or CSS class) that tell AngularJS’s HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children. Angular comes with a set of these directives built-in, like ngBind, ngModel, and ngView. Much like you create controllers and services, you can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.
  • Model : A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. A passive implementation of MVC omits these notifications, because the application does not require them or the software platform does not support them.
  • Scope :  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created automatically when compiled HTML template is executed.)

Backbone.js

backbone.js

Backbone.js is a JavaScript library with a RESTful JSON interface and is based on the model–view–presenter (MVP) application design paradigm. Backbone is known for being lightweight, as its only dependency is on one JavaScript library, Underscore.js. It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized. Backbone was created by Jeremy Ashkenas, who is also known for CoffeeScript.

Backbone.js is composed of the following modules:
  • Models – Models are the heart of any Javascript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.
  • Collections – Collections are ordered sets of models. You can bind “change” events to be notified when any model in the collection has been modified, listen for “add” and “remove” events, fetch the collection from the server, and use a full suite of Underscore.js methods. Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection.
  • Routers – Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it’s now possible to use standard URLs (/page). Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don’t yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL. Views – Backbone views are almost more convention than they are code — they don’t determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view’s render function to the model’s “change” event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.
  • Events – Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments.

Knockout.js

Knockout is a standalone JavaScript implementation of the Model-View-View-Model(MVVM) pattern with templates. Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), Knockout can help you implement it more simply and maintainable.

knockoutjs

knockoutjs

Knockout includes the following features:

  • Declarative bindings – a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Automatic UI refresh (when the data model’s state changes, the UI updates automatically) – automatically updates the right parts of your UI whenever your data model changes.
  • Templating (using a native template engine although other templating engines can be used, such as jquery.tmpl)

Ember.js

Ember.js is an open-source client-side JavaScript web application framework based on the Model-View-Controller (MVC) architectural pattern. It allows developers to create scalable single-page applications by incorporating common idioms and best practices into a framework that provides a rich object model, declarative two-way data binding, computed properties, automatically-updating templates powered by Handlebars.js, and a router for managing application state.

emberjs

 Main concepts are :

  • Models : All the database connections and synching with view happens here.
  • Router : Routers are used to query the model, from their model hook, to make it available in the controller and in the template.
  • Controllers : Controllers makes the bridge between the model and the view or template.
  • Views : Views represent particular parts of your application (the visual parts that the user can see in the browser). A View is associated with a Controller, a Handlebars template and a Route.
  • Component : A Component is a completely isolated View that has no access to the surrounding context.
  • Templates : A template is the view’s HTML markup.
  • Helpers : Handlebars helpers are functions that modify data before it is rendered on the screen.

Basically all the above mentioned framework/library is suited according to the requirement. Like if you want a light weight application with constant database updation and client side logic, then one should opt for backbone.js and if you have a very large application which is maintained by a lot of developers, then Angular.js will be the best solution. Learn one and the others would be much easier to grasp. And stick to the one that you feel is good for your method of development.

Hope you liked it. Thanks for reading. Cheers.

Resources

December 16

How to Add Stroke to a Web Text

Fonts on the web are essentially vector based graphics. That’s why you can display them at 12px or 120px and they remain crisp and relatively sharp-edged. Vector means that their shape is determined by points and mathematics to describe the shape, rather than actual pixel data. Because they are vector, it would make sense if we could do things that other vector programs (e.g. Adobe Illustrator) can do with vector text, like draw a stroke around the individual characters. Well, we can! At least in WebKit.

Example:

h1 {
-webkit-text-stroke-width: 1px;
-webkit-text-stroke-color: black;
}

Or shorthand:

h1 {
-webkit-text-stroke: 1px black;
}

WebKit has your back on that one, you can set the text color with another proprietary property, so you’re safe for all browsers:

h1 {
color: black;
-webkit-text-fill-color: white; /* Will override color (regardless of order) */
-webkit-text-stroke-width: 1px;
-webkit-text-stroke-color: black;
}

Thankyou for reading.

December 16

Google Badge (How to Create a google chat in your own website. Like gtalk)

Note : The following post is quite old and google has removed reference links provided.

What it is

A Google Talk chatback badge allows others to chat with you even if they haven’t signed up for Google Talk on their Google Account or if they don’t have a Google Account. You can put the badge in your blog or website, and people who visit those pages can chat with you. The badge will display your online status (whether you’re available to chat or not) and, optionally, your status message.
What I need in order to create one

You need to be a Google Talk user to create a badge, and you’ll need to be online and available (with a green ball next to your name) in Google Talk to enable people to chat with you. If you’re not a current Google Talk user, you’ll need to create a new Google Account. If you have Gmail on your Google Account, you can use Google Talk with your Gmail username and password. You can also use the Google Talk Gadget; just go to http://www.google.com/talk/ and click ‘Launch Google Talk Gadget.’
Let’s create one!

  1. To create your chatback badge, visit http://www.google.com/talk/service/badge/New. If you’re using a Google Apps account, you can create a chatback badge by visitinghttp://www.google.com/talk/service/a/DOMAIN/badge/New where DOMAIN is the name of your domain.
  2. From the page, copy and paste the HTML into the source of your webpage where you want the badge to be displayed. You’ll know it’s working if you see a large Google Talk bubble showing your current online status along with the message ‘Chat with [your name]‘ (or whatever you selected as your badge title).
To see this application in a live website visit : Datta Global Traders. This is a site which i have created and implemented this feature. Its wasy and fun..
December 11

Javascript & Object Oriented Programming – Objects

JavaScript is an excellent language to write object oriented web applications. It can support OOP concepts because it supports inheritance through prototyping as well as properties and methods. Many developers write off JavaSript as a suitable OOP language because they are so used to the class style of C# and Java. Many people don’t realize that JavaScript supports inheritance. When you write object-oriented code it instantly gives you power, you can write code that can be re-used and that is encapsulated.

OOPs

JavaScript has Prototype based Inheritance and not Class based.

  • All objects are instances.
  • Define and create a set of objects with constructor functions.
  • Create a single object with the new operator.
  • Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
  • Inherit properties by following the prototype chain.
  • Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

and because of all the above mentioned properties, JavaScript supports the concept of Object Oriented Programming.

Objects

JavaScript objects are pretty much similar to real-world objects. Consider a real world object say Monitor. It has properties like height, width, thickness and so on. If you consider a horn, it has properties such as noise level, intensity and so on.

So likewise JavaScript also allows you to create any objects with properties as you want. And when the code is wrapped inside an event, then its perfectly encapsulated. You also can initialize the same object any number of times.

A JavaScript object can be created in many different ways. One such way would be to use the new operator.

Example 1 :

var school = new School();
school.principal = "Mathew";
school.location  = "Trivandrum";
school.students  = "100";

where School is the object, school the instance of the object School and pricipal, location and students will be the properties.

Second method would be to use Object.create();

Example 2 :

var school = Object.create(School,{
    principal: "Mathew",
    location : "Trivandrum",
    students : "100"
});

Another way of creating an object will be through Literals. Using Literal Notations we can create JavaScript objects in the go. You can nest any number of objects inside an object.

Example 3 :

var school = {
    principal : "Mathew",
    location  : "Trivandrum",
    students  : "100"
}

Nesting in Objects is possible here.

Example 4 :

var school = {
    principal : "Mathew",
    location : "Trivandrum",
    students : "100",
    teachers : {
              "English" : "Manju",
              "History" : "D'Costa"
           }
}

Retrieving values from a Javascript object is very simple. The example below itself is a self explanatory one.

Example 5 :

//Object
var school = {
    principal : "Mathew",
    location  : "Trivandrum",
    students  : "100"
}
//Retrieving Property Values
var Principal = school.principal;
var Location  = school.location;
var Students  = school.students;

Objects and properties

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:

objectName.propertyName;

Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let’s create an object named school and give it properties named principal, location and year as follows:

Example 6 :

var school = new Object();
school.principal = "Mathew";
school.location = "TVM";
school.year = 2013;

Properties of JavaScript objects can also be accessed or set using a bracket notation. Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the school object as follows:

Example 7 :

school["principal"] = "Mathew";
school["location"] = "TVM";
school["year"] = 2013;

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

Example 8 :

var myObj = new Object(),
    str = "myString",
    rand = Math.random(),
    obj = new Object();
myObj.type              = "Dot syntax";
myObj["date created"]   = "String with space";
myObj[str]              = "String value";
myObj[rand]             = "Random Number";
myObj[obj]              = "Object";
myObj[""]               = "Even an empty string";
console.log(myObj);

You can also access properties by using a string value that is stored in a variable:

Example 9 :

var propertyName = "principal";
school[propertyName] = "Mathew";
propertyName = "location";
school[propertyName] = "TVM";
propertyName = "year";
school[propertyName] = "2013";

Deleting Properties

You can remove a property by using the delete operator. The following code shows how to remove a property.

Example 10 :

//Creates a new property, school, with two properties, principal and year.
school = new Object;
school.principal = "Mathew";
school.year = 2013;
//Removes the a property, leaving school with only the year property.
delete school.principal;

Inheritance
All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor.

Defining properties for an object type

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object.

The following code adds a year property to all objects of type School, and then assigns a value to the year property of the object school.

Example 11 :

School.prototype.year = null;
school.year = "2013";

In JavaScript, almost everything is an object. All primitive types except null and undefined are treated as objects. They can be assigned properties (assigned properties of some types are not persistent), and they have all characteristics of objects.

Thankyou for reading. Cheers.

December 9

Concept of Prototype in Javascript

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.

When you define a function within JavaScript, it comes with a few pre-defined properties; one of these is the illusive prototype.

Each object in javascript actually has a member called “prototype”, which is responsible for providing values when an object is asked for them. Adding a property to the prototype of an object will make it available to that object, as well as to all of the objects which inherit from it.

object.prototype.name=value

Prototype allows you to make classes. if you do not use prototype then it becomes a static.

Here is a short example :

var obj = new Object();
obj.test = function() { alert('Hello?'); };

In the above case, you have static function call test. This function can be accessed only by obj.test where you can imagine obj to be a class.

where as in the below code

function obj()
{
}
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();

The obj has become a class which can now be instantiated. Multiple instances of obj can exist and they all have the test function.

  • A function’s prototype: A function’s prototype is the object instance that will become the prototype for all objects created using this function as a constructor.
  • An object’s prototype: An object prototype is the object instance from which the object is inherited.

Prototype inheritance

Prototype inheritance is a form of object-oriented code reuse. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical.

  • In classical inheritance, the programmer writes a class, which defines an object. Multiple objects can be instantiated from the same class, so you have code in one place which describes several objects in your program. Classes can then be organized into a hierarchy, furthering code reuse. More general code is stored in a higher-level class, from which lower level classes inherit. This means that an object is sharing code with other objects of the same class, as well as with its parent classes.
  • In the prototypal inheritance form, objects inherit directly from other objects. All of the business about classes goes away. If you want an object, you just write an object. But code reuse is still a valuable thing, so objects are allowed to be linked together in a hierarchy. In javascript, every object has a secret link to the object which created it, forming a chain. When an object is asked for a property that it does not have, its parent object is asked… continually up the chain until the property is found or until the root object is reached.

The following example can help give more insight into the whole Prototype Concept.

Consider the following scenario :

We have a Employee class, there are different types of Employees like Managers, Supervisors, Agents etc. But each type is actually inheriting Employee.

Example:

	//Define a functional object to hold employee in JavaScript
	var Employee = function(name) {
	    this.name = name;
	};
	//Add dynamically to the already defined object a new getter
	Employee.prototype.getName = function() {
	    return this.name;
	};
	//Create a new object of type Employee
	var judy= new Employee("Judy");
	//Try the getter
	alert(judy.getName());
	//If now I modify employee, also Judy gets the updates
	Employee.prototype.alertMyName = function() {
	    alert('Hello, my name is ' + this.getName());
	};
	//Call the new method on john
	judy.alertMyName();

Here in above code we extended the base object, now we will create a child object and inherit it from base class.

	//Create a new object of type Manager by defining its constructor.
	// It's not related to Employee for now.
	var Manager = function(name) {
	    this.name = name;
	};
	//Now I link the objects and to do so, we link the prototype of Manager
	//to a new instance of Employee. The prototype is the base that will be
	//used to construct all new instances and also, will modify dynamically
	//all already constructed objects because in JavaScript objects retain
	//a pointer to the prototype
	Manager.prototype = new Employee();
	//Now I can call the methods of Employee on the Manager, let's try,
	//first I need to create a Manager.
	var myManager = new Manager('John Smith');
	myManager.alertMyName();
	//If I add new methods to Employee, they will be added to Manager,
	//but if I add new methods to Manager they won't be added
	//to Employee. Example:
	Manager.prototype.setSalary = function(salary) {
	    this.Salary = salary;
	};
	Customer.prototype.getSalary = function() {
	    return this.Salary;
	};
	//Let's try:
	myManager.setSalary(30000);
	alert(myManager.getSalary());

While as said I can’t call setSalary(), getSalary() on a Employee. Because parent class does not have child class function.

The ‘prototype’ property is not the real prototype (__proto__) of the function.

Foo.__proto__ === Foo.prototype //=> false

This of course generates a lot of confusion as people use the term ’prototype’ to refer to different things. I think that a good clarification is to always refer to the special ’prototype’ property of functions as ’the function prototype’, never just ’prototype’.

The ‘prototype’ property points to the object that will be asigned as the prototype of instances created with that function when using ’new’. Confusing? This is easier to explain with an example:

function Person(name) {
  this.name = name;
}
// the function person has a prototype property
// we can add properties to this function prototype
Person.prototype.kind = ‘person’
// when we create a new object using new
var zack = new Person(‘Zack’);
// the prototype of the new object points to person.prototype
zack.__proto__ == Person.prototype //=> true
// in the new object we have access to properties defined in Person.prototype
zack.kind //=> person

Thankyou for reading. Cheers.

Category: Javascripts | 2 Comments
December 8

JavaScript Closures

Closures Are Not Magic

This page explains closures so that a programmer can understand them — using working JavaScript code. It is not for gurus or functional programmers.

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

This article is intended for programmers with some programming experience in a mainstream language, and who can read the following JavaScript function:

function sayHello(name) {
    var text = 'Hello ' + name;
    var sayAlert = function() { alert(text); }
    sayAlert();
}

An Example of a Closure

Two one sentence summaries:

  • A closure is the local variables for a function — kept alive after the function has returned, or
  • A closure is a stack-frame which is not deallocated when the function returns (as if a ‘stack-frame’ were malloc’ed instead of being on the stack!).

The following code returns a reference to a function:

function sayHello2(name) {
    var text = 'Hello ' + name; // Local variable
    var sayAlert = function() { alert(text); }
    return sayAlert;
}
say2 = sayHello2('Bob');
say2(); // alerts "Hello Bob"

Most JavaScript programmers will understand how a reference to a function is returned to a variable in the above code. If you don’t, then you need to before you can learn closures. A C programmer would think of the function as returning a pointer to a function, and that the variables sayAlert and say2 were each a pointer to a function.

There is a critical difference between a C pointer to a function and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.

The above code has a closure because the anonymous function

function() { alert(text); }

is declared inside another function, sayHello2() in this example. In JavaScript, if you use the function keyword inside another function, you are creating a closure.

In C, and most other common languages after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2().

function() { alert(text); } // Output of say2.toString();

Click the button above to get JavaScript to print out the code for the anonymous function. You can see that the code refers to the variable text. The anonymous function can reference text which holds the value ‘Jane’ because the local variables of sayHello2() are kept in a closure.

The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in — similar to how delegates are a method pointer plus a secret reference to an object.

More examples

For some reason, closures seem really hard to understand when you read about them, but when you see some examples you can click to how they work (it took me a while). I recommend working through the examples carefully until you understand how they work. If you start using closures without fully understanding how they work, you would soon create some very weird bugs!

Example 3

This example shows that the local variables are not copied — they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!

function say667() {
    // Local variable that ends up within closure
    var num = 666;
    var sayAlert = function() { alert(num); }
    num++;
    return sayAlert;
}

Example 4

All three global functions have a common reference to the same closure because they are all declared within a single call to setupSomeGlobals().

function setupSomeGlobals() {
    // Local variable that ends up within closure
    var num = 666;
    // Store some references to functions as global variables
    gAlertNumber = function() { alert(num); }
    gIncreaseNumber = function() { num++; }
    gSetNumber = function(x) { num = x; }
}

The three functions have shared access to the same closure — the local variables of setupSomeGlobals() when the three functions were defined.

Note that in the above example, if you click setupSomeGlobals() again, then a new closure (stack-frame!) is created. The old gAlertNumber, gIncreaseNumber, gSetNumber variables are overwritten with new functions that have the new closure. (In JavaScript, whenever you declare a function inside another function, the inside function(s) is/are recreated again each time the outside function is called.)

Example 5

This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.

function buildList(list) {
    var result = [];
    for (var i = 0; i < list.length; i++) {
        var item = 'item' + list[i];
        result.push( function() {alert(item + ' ' + list[i])} );
    }
    return result;
}
function testList() {
    var fnlist = buildList([1,2,3]);
    // Using j only to help prevent confusion -- could use i.
    for (var j = 0; j < fnlist.length; j++) {
        fnlist[j]();
    }
}

The line result.push( function() {alert(item + ‘ ‘ + list[i])} adds a reference to an anonymous function three times to the result array. If you are not so familiar with anonymous functions think of it like:

pointer = function() {alert(item + ' ' + list[i])};
result.push(pointer);

Note that when you run the example, “item3 undefined” is alerted three times! This is because just like previous examples, there is only one closure for the local variables for buildList. When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the current value for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of ‘item3′).

Example 6

This example shows that the closure contains any local variables that were declared inside the outer function before it exited. Note that the variable alice is actually declared after the anonymous function. The anonymous function is declared first; and when that function is called it can access the alice variable because alice is in the closure. Also sayAlice()() just directly calls the function reference returned from sayAlice() — it is exactly the same as what was done previously, but without the temporary variable.

function sayAlice() {
    var sayAlert = function() { alert(alice); }
    // Local variable that ends up within closure
    var alice = 'Hello Alice';
    return sayAlert;
}
sayAlice()();

Tricky: note also that the sayAlert variable is also inside the closure, and could be accessed by any other function that might be declared within sayAlice(), or it could be accessed recursively within the inside function.

Example 7

This final example shows that each call creates a separate closure for the local variables. There is not a single closure per function declaration. There is a closure for each call to a function.

function newClosure(someNum, someRef) {
    // Local variables that end up within closure
    var num = someNum;
    var anArray = [1,2,3];
    var ref = someRef;
    return function(x) {
        num += x;
        anArray.push(num);
        alert('num: ' + num +
            '\nanArray ' + anArray.toString() +
            '\nref.someVar ' + ref.someVar);
      }
}
obj = {someVar: 4};
fn1 = newClosure(4, obj);
fn2 = newClosure(5, obj);
fn1(1); // num: 5; anArray: 1,2,3,5; ref.someVar: 4;
fn2(1); // num: 6; anArray: 1,2,3,6; ref.someVar: 4;
obj.someVar++;
fn1(2); // num: 7; anArray: 1,2,3,5,7; ref.someVar: 5;
fn2(2); // num: 8; anArray: 1,2,3,6,8; ref.someVar: 5;

Summary

If everything seems completely unclear then the best thing to do is to play with the examples. Reading an explanation is much harder than understanding examples. My explanations of closures and stack-frames, etc. are not technically correct — they are gross simplifications intended to help understanding. Once the basic idea is grokked, you can pick up the details later.
Final points:

  • Whenever you use function inside another function, a closure is used.
  • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and within eval you can even create new local variables by using eval(‘var foo = …’)
  • When you use new Function(…) (the Function constructor) inside a function, it does not create a closure. (The new function cannot reference the local variables of the outer function.)
  • A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.
  • It is probably best to think that a closure is always created just on entry to a function, and the local variables are added to that closure.
  • A new set of local variables is kept every time a function with a closure is called (given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).
  • Two functions might look like they have the same source text, but have completely different behaviour because of their ‘hidden’ closure. I don’t think JavaScript code can actually find out if a function reference has a closure or not.
  • If you are trying to do any dynamic source code modifications (for example:
    myFunction = Function(myFunction.toString().replace(/Hello/,'Hola'));

    ), it won’t work if myFunction is a closure (of course, you would never even think of doing source code string substitution at runtime, but…).

  • It is possible to get function declarations within function declarations within functions — and you can get closures at more than one level.
  • A closure is the term for both the function along with the variables that are captured. Note that I do not use that definition in this article!
  • Closures in JavaScript differ from those normally found in functional languages.

Please note that I am not a guru on JavaScript — nor on closures.

Thanks for reading.

Category: Javascripts | 1 Comment
December 5

Ajax

If you are totally new to AJAX (which stands for stands for Asynchronous Javascript And XML), the AJAX entry on wikipedia is a good starting point:

Like DHTML and LAMP, AJAX is not a technology in itself, but a group of technologies. AJAX uses a combination of:

  • HTML and CSS for marking up and styling information.
  • The DOM accessed with JavaScript to dynamically display and interact with the information presented.
  • A method for exchanging data asynchronously between browser and server, thereby avoiding page reloads. The XMLHttpRequest (XHR) object is usually used, but sometimes an IFrame object or a dynamically added tag is used instead.
  • A format for the data sent to the browser. Common formats include XML, pre-formatted HTML, plain text, and JavaScript Object Notation (JSON). This data could be created dynamically by some form of server-side scripting.

As you can see, from a pure technological point of view, there is nothing really new here. Most of AJAX parts were already there in 1994 (1999 for the XMLHttpRequest object). The real novelty was to use these parts together as Google did with GMail (2004) and Google Maps (2005). Actually, both sites contributed heavily to the promotion of AJAX.

A picture being worth a thousand words, below a diagram that illustrates the communication between the client and the remote server, as well as the differences between the classic and the AJAX-powered applications:

For the orange part, you can do everything by hand (with the XMLHttpRequest object) or you can use famous JavaScript libraries like jQuery, Prototype, YUI, etc to “AJAXify” the client-side of your application. Such libraries aim to hide the complexity of JavaScript development (e.g. the cross-browser compatibility), but might be overkill for a simple feature.

On the server-side, some frameworks can help too (e.g. DWR or RAJAX if you are using Java), but all you need to do is basically to expose a service that returns only the required informations to partially update the page (initially as XML/XHTML – the X in AJAX – but JSON is often preferred nowadays).

GET or POST?

GET

  • GET requests can be cached
  • GET requests remain in the browser history
  • GET requests can be bookmarked
  • GET requests should never be used when dealing with sensitive data
  • GET requests have length restrictions
  • GET requests should be used only to retrieve data

POST

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length

Example 1 (Core Ajax – GET) :

xmlhttp.open("GET","demo.php?fname=Henry&lname=Ford",true);
xmlhttp.send();

The above method will pass fname and lname to an external page called demo.php.

Example 2 (jQuery Equivalent- GET) :

$.ajax({
  url:"demo.php",
  data:'fname=Henry&lname=Ford',
  type: "GET"
});