JSON for idiots
February 27th, 2008 Filed Under CSS, Javascript, Tips & Tricks, json, snippet
Please forgive me for the title of this article. It doesn’t mean you are an idiot. And if you think you are … after reading this article you will not be one any more.
This is for all my friends who are into UI but don’t know the proper usage of JSON Object. Or the people who have heard about JSON but never been exposed to it.
JSON stands for Java Script Object Notation. JSON is a shorthand notation for declaring or constructing a custom object in Javascript.
“At first you must
Shake off the rust”
Let us be clear about what is an object in javascript. First question first… Can we create class, object etc in javascript?? Actually speaking “NO”. Javascript is not a Object Oriented Language. But it allows you to declare custom objects in addition to its primitive object types. So we can say that javascript is an object based language. So like other OO languages you cannot declare a class and then its constructor and then its object.
But what you can certainly do is, you can straight-away create a constructor which acts like a class and a constructor both.
So how can we create a class-constructor and instantiate an object out of it will be discussed some other time.
But for now we dig down to the definition of an object.
An object is an entity or collection of key & value pairs. A value can be of any kind of primitive data type. It can be even another object too.
Now I will cite an example of an object entity called “student”. We take a student whose name is Vivek and his age is 16 yrs.
So our object is having a key called “name” and the value for that key is “Vivek”. There is another key called age and the value of this key is “16″.
So if we translate that to JSON it becomes like this:
var student = {name: "Vivek", age:16};
So, if you need to access this object you say “Give me the student name and his age”.
And using javascript you translate it in the following syntax to alert one-by-one:
alert(student.name);
alert(student.age);
Now you feel like a programmer, isn’t it? Kewl.
Now lets check if we can go a bit more complex in it. The student has two phone numbers to get contacted. Actually he also has an email address. So if you create a category called “contacts” you can club all these items in it. So this also can become a key value pairs and hence, become an object:
What I mean is this:
var contacts = {landline: "918041278882", mobile: "919243176274", email: "vivek.pohre@gmail.com"};
But wait we actually wanted this to be a part of the student object… right? OK thats fair … we will push this to the student object.
So now after pushing the contacts to the student object, it looks like this:
var student = {// YOU CAN INFACT INDENT THE JSON OBJECT IN THIS WAY FOR BETTER READABILITY
name : "Vivek",
age : 16,
contacts :
{
landline: “918041278882″,
mobile : “919243176274″,
email : “vivek.pohre@gmail.com”
}
};
Wow, Now you know what is all that hi-fi code in the javascript libraries… hurray!!
OK but how do you access it again?
See how:
alert(student.contacts.landline);
alert(student.contacts.mobile);
alert(student.contacts.email);
So lets revisit the whole thing and use the technical terms to impress your colleagues:
I have an object called student which have different attributes(keys we say) like name, age, contacts and we can have some methods too for it. OK till attributes it was clear but what the well is method?
A method is a process which does something. What does it do? For example, if you want the student object to speak something about itself. Say when you command the student to speak it tells you his name, his age and his email id.
var student = {// YOU CAN INFACT INDENT THE JSON OBJECT IN THIS WAY FOR BETTER READABILITY
name : "Vivek",
age : 16,
contacts :
{
landline: "918041278882",
mobile : "919243176274",
email : "vivek.pohre@gmail.com"
},
speak: function()
{
alert(”My name is ” + this.name);
alert(”My age is ” + this.age);
alert(”My email id is ” + this.contacts.email)
}
};
OKAY… so now when you command by saying:
student.speak();
It throws 3 alerts which says My name is Vivek, My age is 16 and My email id is vivek.pohre@gmail.com.
Grreeeeeeeeeeat.
Have you ever heard people speaking about sending and receiving data in JSON using ajax?
So it is not so very big deal. You must be knowing that in ajax you get a string. Now if you assign this string to a temporary variable and evaluate it … you get a readymade object.
That means:
If you have a list of students on the HTML page and when a user clicks on a link. The interaction should be the speak command for that particular user.
Oho… how do you do that? Very simple… create an ajax call like this:
function commandStudent(name)
{
var returnText = ajax.gets("http://www.something.com/student?name=" + name);
if(returnText)
{
var tempStudent = eval(returnText);
tempStudent.speak();
}
}
Great man … now you are an ajax guru. Ask your manager to reevaluate your salary.
I ll explain sometime about how to send data from client side to the server using ajax and JSON.
“Your heart bears the fruit
When you go to the root”
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
InnerHTML does not grab form values in Firefox?
February 26th, 2008 Filed Under Javascript, Tips & Tricks, browser, gyan, snippet
Assignment of attribute values in Firefox, InnerHTML does not grab form values in Firefox:
Not all the attributes can be set by the .syntax using javascript as a permanent assignment. For example if you wan to assign a event handler onclick to an object, you need to use .setAttribute instead of .onclick.
The good thing is that setAttribute works in IE too.
So unless the attribute is set using .setAttribute, the DOM in Firefox or “Gecko” based browsers does not register the change.
I would like to demonstrate for clear understanding.
I have the following code:
<!doctype html public “-//w3c//dtd html 4.0 transitional//en”>
<html>
<head>
<title> new document </title>
<meta name=”generator” content=”editplus”>
<meta name=”author” content=”">
<meta name=”keywords” content=”">
<meta name=”description” content=”">
</head>
<BODY>
<form>
<input type=”text” name=”myText”/>
<input type=”button” value=”check” onclick=”checkIt(this)”/>
</form>
<script>
function checkIt(obj)
{
obj.form[’myText’].value = “hi there”;
alert(obj.form.innerHTML); // I EXPECT “myText” TO THROW THE VALUE AS AN ATTRIBUTE IN THIS ALERT
}
</script>
</body>
</html>
Here I expect “myText” to throw the value as an attribute in the alert, but the result is different for IE and FF.
In IE I get this:
and in FF I get this:
So to overcome this problem we need to use the following code:
function checkIt(obj)
{
obj.form[’myText’].setAttribute(”value”, “hi there”);
alert(obj.form.innerHTML); // I EXPECT “myText” TO THROW THE VALUE AS AN ATTRIBUTE IN THIS ALERT
}
Now it grabs the expected result.
Great to know that right?
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
Tata Nano
February 25th, 2008 Filed Under Uncategorized
Since the Tata Nano is announced here including me everyone is eager to know what is the time it will hit the market. Everyone despite of knowing the disadvantages for the environment and never seen traffic jams, waiting for have one at their doorstep. I live in Bangalore and I hear that everyone who has a bike is talking about having a car, but because of the fuel costs going so high day by day they feel its like having a pet elephant standing at their doorsteps.
The green city and the AC of India is getting spoiled day by day. I admit, I am the one who is a part in doing so. I left my village to earn money in this city. Since then I have been watching the city’s greeneries getting cut everyday. For example the Sarjapura Road which joins Koramangala is getting widen. This road was known for having big green trees on both the sides. I used to feel so proud when my guests used to appreciate this city for its greeneries.
Not only that I have also heard that the most important reason for the widening of roads is the expectation of nano on the roads and hence the management of the traffic will worsen.
I don’t know if the introduction of Tata Nano is a Bliss or a Curse for us. The car is going to be hit for sure but I think it will take atleast 2 hours to reach office once the car is pushed in the market
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
New Features in Firefox 3 (part 1)
February 22nd, 2008 Filed Under CSS, Javascript, Technology, browser
Hot and Cool features in Firefox #1
Right now firefox 3 is in its beta stage and the beta 3 is being pulled currently by the developers to test. Till now I didn’t find any thing which should say its a firefox bug.
Today I am going to present you some of the most discussed features and changes of firefox 3.
HTML: If you have ever come across the character set problem in Firefox; Be happy its fixed. For those who didn’t know this, I will explain a bit. Let us say you have a particular character set for a page declared. Now if you have a frame or an iframe in your page, let us say from a third party or from your own resources which needs to show a different character set .. it used to inherit the character set from the parent. For a long time, FF was not releasing any patch for this. Thank god somebody reported and its fixed now.
Javascript: Now Firefox supports javascript version 1.8. But as always, I am so skeptical about the usage. No body will forget Internet Explorer not having javascript 1.8 and hence how many people develop web apps and sites to run only on Firefox? But surely some of the features keeps the browser aside from others and may be considered for this. Let’s go ahead. Know more about javascript 1.8
Online/Offline events: Now I came to know the Google’s idea of having Gears at the place. Since FF was developing this feature Google Gears has clubbed this and two more features from FF and made it a plugin for all the browsers a user have. Although its not a bad idea. Egoistic Microsoft wouldn’t have done this at all. O.K. so let me tell you this feature in detail: This feature lets you know when the connection with the internet/intranet is available/unavaialble. This saves you from writing your own rings and eylets to check the connection availability. Very useful for offline apps capability. It is a property which sits in the navigator object and can be accessed by the syntax ‘navigator.onLine’ and the possible values are “ONLINE”/”OFFLINE”. The events can be fired from document, window or document.body. That means on the body tag you can write ononline=”” or onoffline=”” and from event attaching javascript you can write window.ononline or document.onoffline etc.
Cross-Site-Ajax: Yeah.. now thats possible. No need to use friendly iFrames(good name, no hifi technology). The W3C’s implementation guidline for access control states the control over who-can and can-not request from a browser. For example if I have a web service and I want my subscriber to use my service through ajax, I need to implement this: Access-Control: allow <jayanthsharma.com> on your page/servlet header. Now my subscriber can use my data to do mashups or whatever way he wants to present the data. No idea when IE will have the same capability. Untill then we may just endup by saying, “You must use Firefox 3 to access this site” … not a good statement though.
CSS Changes: FF3 now have alternative stylesheet support. This I read as a recommendation by W3C way back in 2000 or 2001. The new CSS implementation have some cool features, I’ll just discuss few of them:
a) rgba() and hsla(): red,green,blue,alpha and hue,saturation,luminosity,alpha. Whoot photoshop users. Time to celebrate!!
b) kerning and ligatures for text: Again its a feature from image editors like photoshop. It now supports the kerning and anti-aliasing for your text to look as good as in Photoshop. A bit slower process but worth having in the browsers. I don’t see the time away when banner ads can be designed using browser capabilities(Adobe has to purchase mozilla).
c) Hyphenation: Again something like photoshop. This feature was too much awaited for years. Now you can have a single string continuous which will ultimately break if there is no space horizontally. But what about previous versions? Can’t do anything about it… (booohooo) It will take at least 2 years to forget about the current browsers I presume.
Protocol Handling: There is a cool and certainly bad feature this time in FireFox 3. This features allows you to specify the protocol handler. For example if you have declared a protocol handler the “mailto” protocol like this:
navigator.registerProtocolHandler(”mailto”, “https://mail.google.com/mail?view=cm&tf=0&to=%s”, “GMAIL”);
and suppose you have a tag in your page like this:
<a href="http://www.vivekpohre.com/wp-admin/%E2%80%9Dmailto:vivek.pohre@gmail.com%E2%80%9D">Vivek Pohre</a>
Then instead of having his preferred email client a user will be thrown to the gmail application. Can’t digest this amore.
This list isn’t quite exhaustive. For more information, check out CSS Improvements in Firefox 3.
There is a lot more in Firefox 3 .. the other parts I would publish in subsequent posts.
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
How to optimize your site
February 20th, 2008 Filed Under CSS, Javascript, Technology, Tips & Tricks, browser, gyan
Optimization means “Most desired possibility under a restriction expressed or implied”.
Why:
We need to optimize our site so that the pages come with minimum flicker and downloads at the light speed. Some of the audience will also say why we need to optimize so much when the broadband speed is growing up higher and higher. The answer from my experience would be .. “Why to spend more money when I know I can get more things by spending the same amount of money?”
By keeping things unoptimized we are doing bad both to the user and ourselves. Most affected is the user and hence our business. We force our users to spend more data when they visit our site. So their money gets hogged up by the ISPs. Moreover even our business is not benefited out of it. The other thing is time. If your site is getting downloaded to the users in no time the user is happy because the user feels that he/she doesn’t have to waste their time in gathering some information. Doesn’t matter how lazy the user is … the user doesn’t want us to be lazy. And that is the key which gives us money directly or indirectly.
So when someone speaks about optimization he/she has to always keep the bigger picture in mind.
In order to optimize your site you need to take care of these thing:
1) Compress your images
2) Club/merge your images
3) Be miser in writing code
4) Deliver your assets from CDNs
5) Properly position your js calls
6) Keep your site accessible
7) Expire your assets in longer periods
8 ) Follow web standards in laying out
Now I am explaining each of the points one by one:
1) Compress your images: Most of the times I have seen people using images which are not compressed using the right compression utility. When I say optimize image I mean also decide in which format should be used to save the image.
The widely used and supported formats by all the A-Grade browsers are :
a) Gif: You choose this format when you see your images are flat colored. Reason being it uses the allowed color gamut and shares the color information with all the defined pixels. So, the more colors you allow the more the size of the image. For example, if you are saving an image which uses only 4 or 5 colors then you choose this format. Also you use this format when you need a clear transparent part in you image.b) Jpeg: This format is used when you see some gradients(colors harmonizing from one range to another). In this case if you use .gif format your color gamut will increase and so your image size. The jpeg image compression saves the shares the pattern all over the image and common patterns are saved as single information and tiled across. Hence if you have an image with a gradient of sky blue to white at 90 degrees then no matter how wide image you save, the file size increases only marginally.
c) Png: This format is more or less same as the Gif format, but has a capability of saving a transparent part with a shade of some color. i.e., starting from some color and ending at transparent. For example you save an image which has a shadow effect.
2) Club/Merge your images: We use lots of small small images for a module or lets say the common parts of our pages. Rather than creating these many images you can make a matrix of such images and call them as the span or div backgrounds and position them accordingly. This saves you unnecessary calls to different assets and the download time drastically comes down. One would say how does it matter? It is only a 43 bytes images. For this I would say that you need to install firebug and see the request and response headers which are the part of a single image call. Its huge data.
3) Be miser in writing code: Your browser feels bliss when your page downloads in a second. The less the code is on the page the lighter is the page. Yeeaah so whats the big deal in that statement? The big deal is that everyone knows but no one cares. Write as less code as you can … make image names as smaller as you can. Put image paths or URLs as smaller as you can. Be a “kanjoos makkhichoos”(an indian proverb)…meaning the great miser. Cut down in naming your css classes.
In javascript use a library to reuse the common codes… jQuery is the one I would suggest. For the css you may merge all the float lefts into single float left having different selectors declared at once. If you don’t get on that revert back to me.
4) Deliver your assets from CDNs: Those of you who don’t know what a CDN is … “A Content Delivery Network (CDN) provides fee-for-service delivery of streaming content via the Internet. Their network consists of linked “edge” servers throughout the Internet that help reduce network congestion and server overload for content delivered”. So if you can use CDN your assets delivery becomes lightning fast. Just try googling around for the “CDN servers”
5) Properly position your js calls: Your js file calls actually halts the display of your page untill the whole file is loaded and interpreted by the browser. You may not realize that if you have less amount of code written in the js files. Whatever is the case you should always make a habit to call only the js libraries inside the head tag. Rest all of them should be called just before you end your html tag. So what happens is your page is displayed fully and the user is not frustrated by seeing a blank white screen. Believe me a users blood boils when he/she sees the blank screen.
6) Keep your site accessible: This point tells you that your site should be accessible in the conditions when there is no javascript in a browser and all the images are off and only the text and hyperlinks works properly. The real reason behind being an accessible site is to be accessible to the disabled and accessible to the page readers. So if you have given alt content to all the important displayed images the page readers will read and tell that to a blind person accessing your site. There are hell lot of things related to this for which I will write a different story some day.
7) Expire your assets in longer periods: What does it mean? It means that every asset(image, page, css, cookie, js, flv, wvm) has a header called expire. And it speaks about the expiration date of that asset. So if your asset doesn’t expire till a longer future time, the browser basically serves that asset from the cache(locally stored version). Hence the first time a user comes to your page it may take some time to download your assets, but the next time it serves from the cache. So the expiry date should be set on the next release anticipated date so that after that your user should get a new content if changed. There is some complexity around this, which I will tell later how to handle it.
8 ) Follow web standards in laying out: Tables are tables they are not frames and they are not containers for your layout. There is a special tag created for layout called division(div) where you should stuff your content. Table is a chart where you display a list of information. So promise me … next time you will not do a misuse of table. And love Div for layouts.
If your site or page has these 8 points checked, I bet your site is one of the worlds’ best site. And I thank you for doing such a wonderful job. Enjoy madi !!
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment



