How To Parse JSON in Javascript – Read a JSON File With JQuery
JQuery has a neat function that allows us to read external and local JSON files.
jQuery.getJSON( url, [data], [callback] )
The first parameter of this function, the URL you are planning to read, is required. The second parameter is used if you need to POST data to the URL. Last but no least, the callback function, although not required, is almost always necessary.
Important: The URL can be to a local or external file. If the file is in another server the URL must contain a callback variable. You’ll see how this works in the next paragraphs.
The Json File
Rather than making my own JSON file, like I’ve done for previous XML and JSON tutorials, I’ve decided that we’ll use Twitter’s search API this time.
Twitter’s search API has many different search options, but you only need to know about the callback and query “q” options.
Most basic Twitter search URL.
http://search.twitter.com/search.json?callback=foo&q=google+wave
Although required in the URL, your script does not have to have a callback function or variable. Just give the callback a value of “?” like this.
http://search.twitter.com/search.json?callback=?&q=google+wave
Important: Different APIs have different callback URL names, flickr’s API for example uses “jsoncallback” instead of “callback” in the URL. Always read the API docs very carefully.
Now that you know what it takes to query Twitter, take a look a sample response.
{"results":[
{"text":"@twitterapi http:\/\/tinyurl.com\/ctrefg",
"to_user_id":396524,
"to_user":"TwitterAPI",
"from_user":"jkoum",
"id":1478555574,
"from_user_id":1833773,
"iso_language_code":"nl",
"source":"<a href="http:\/\/twitter.com\/">twitter<\/a>",
"profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/118412707\/2522215727_a5f07da155_b_normal.jpg",
"created_at":"Wed, 08 Apr 2009 19:22:10 +0000"}],
"since_id":0,
"max_id":1480307926,
"refresh_url":"?since_id=1480307926&q=%40twitterapi",
"results_per_page":15,
"next_page":"?page=2&max_id=1480307926&q=%40twitterapi",
"completed_in":0.031704,
"page":1,
"query":"%40twitterapi"}]
}
This response only returned one result but you need not worry about that.
In this API the set of results begin with “[” and end with “]”. Every time you see this symbols it means that you loop through the set in them.
Retrieving The Results
Let’s begin building our JSON reading script. This script will be a twitter search script, so we are going to need a text box, a button and a div where we show the results.
<input type="text" id="query" /><button>Search</button> <div id="results"></div>
The JQuery part will have the following structure
$(document).ready(function(){
// twitter api's base url
var url="http://search.twitter.com/search.json?callback=?&q=";
// we'll store the search term here
var query;
// when the user clicks the button
$("button").click(function(){
// get value in the search box and store it in the variable
query=$("#query").val();
// get the json file
});
});
Okay, we have the basic set up, it’s now time to build the getJSON part.
Our URL parameter will be the URL concatenated with the query (url+query). Since we are not posting data we don’t need the second parameter. The function getJSON returns a JSON object which we will use as parameter for the callback function.
// get the json file
$.getJSON(url+query,function(json){
// this is where we can loop through the results in the json object
});
Looping Through The Results
Notice that we passed an object called “json” to the callback function, you can change the name of this object but I think json makes sense. This object now contains all the json data we need, all we need to to now is loop through the results sent from twitter.
// this is where we can loop through the results in the json object
$.each(json.results, function(i,tweet){
// this is where we do what we want with the tweet
});
Let’s break down the loop. the first parameter “json.results” refers to the array in the object we want to loop through, since the only array in the json response from the Twitter search API is “results” we say json.results. The second parameter, the function, has two parameters and you can change the name of them if you want to, I used “i” and “tweet”.
The the “i” refers to the current number of loops and you could use if for example to display the number of results you got from the query. The “tweet” refers to the current tweet, so you can refer to any of the following keys by prepending the word “tweet” before them.
{
"text":"@twitterapi http:\/\/tinyurl.com\/ctrefg",
"to_user_id":396524,
"to_user":"TwitterAPI",
"from_user":"jkoum",
"id":1478555574,
"from_user_id":1833773,
"iso_language_code":"nl",
"source":"<a href="http:\/\/twitter.com\/">twitter<\/a>",
"profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/118412707\/2522215727_a5f07da155_b_normal.jpg",
"created_at":"Wed, 08 Apr 2009 19:22:10 +0000"
}
To get the username from which the tweet originated you would use tweet.from_user , to get the actual tweet you would use tweet.text.
Let’s put the profile image and tweet in our div tag.
// this is where we can loop through the results in the json object
$.each(json.results,function(i,tweet){
// this is where we do what we want with each tweet
$("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
});
The full script
<input type="text" id="query" /><button>search</button><br />
<div id="results">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://search.twitter.com/search.json?callback=?&q=';
var query;
$('button').click(function(){
query=$("#query").val();
$.getJSON(url+query,function(json){
$.each(json.results,function(i,tweet){
$("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
});
});
});
});
</script>
More JSON API’s
Here’s a list of some API’s that return JSON for you to pratice. Let me know if you of more.
Flickr
bit.ly
Best Buy
Javascript equivalent for PHP's strlen
This article is part of the ‘Porting PHP to Javascript’ Project, which aims to decrease the gap between developing for PHP & Javascript.
A lot of people are familiar with PHP’s functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.
Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.
PHP strlen
Description
strlen – Get string length
int strlen( string string )
Returns the length of the given string.
Parameters
- stringThe string being measured for length.
Return Values
The length of the string on success, and 0 if the string is empty.
See Also
Download php.js
To easily include it in your code, every function currently available is stored in
Normal
- uncompressed source: php.js
- minified: php.min.js [recommended]
- compressed: php.packed.js
Namespaced What is ‘namespaced?’
- uncompressed source: php.namespaced.js
- minified: php.namespaced.min.js
- compressed: php.namespaced.packed.js
To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it
Speed Up Your Javascript Load Time
Speed Up Your Javascript Load Time
Javascript is becoming increasingly popular on websites, from loading dynamic data via AJAX to adding special
effects to your page.
Unfortunately, these features come at a price: you must often rely on heavy Javascript libraries that can add dozens
or even hundreds of kilobytes to your page.
Users hate waiting, so here are a few techniques you can use to trim down your sites.
Find The Flab
Like any optimization technique, it helps to measure and figure out what parts are taking the longest. You might find
that your images and HTML outweigh your scripts. Here’s a few ways to investigate:
1. The Firefox web-developer toolbar lets you see a breakdown of file sizes for a page (Right Click > Web
Developer > Information > View Document Size). Look at the breakdown and see what is eating the majority if
your bandwidth, and which files:

2. The Firebug Plugin also shows a breakdown of files – just go to the “Net” tab. You can also filter by file type:

3. OctaGate SiteTimer gives a clean, online chart of how long each file takes to download:

Disgusted by the bloat? Decided your javascript needs to go? Let’s do it.
Compress Your Javascript
First, you can try to make the javascript file smaller itself. There are lots of utilities to “crunch” your files by
removing whitespace and comments.
You can do this, but these tools can be finnicky and may make unwanted changes if your code isn’t formatted
properly. Here’s what you can do:
1. Run JSLint (online or downloadable version) to analyze your code and make sure it is well-formatted.
2. Use Rhino to compress your javascript. There are some online packers, but Rhino actually analyzes your source
code so it has a low chance of changing it as it compresses, and it is scriptable.
Install Rhino (it requires Java), then run it from the command-line:
java -jar custom_rhino.jar -c myfile.js > myfile.js.packed 2>&1
This compresses myfile.js and spits it out into myfile.js.packed. Rhino will remove spaces, comments and shorten
variable names where appropriate. The “2>&1″ part means “redirect standard error to the same location as the
output”, so you’ll see any error messages inside the packed file itself (cool, eh? Learn more here.).
Using Rhino, I pack the original javascript and deploy the packed version to my website.
Debugging Compressed Javascript
Debugging compressed Javascript can be really difficult. I suggest creating a “debug” version of your page that
references the original files. Once you test it and get the page working, pack it, test the packed version, and then
deploy.
If you have a unit testing framework like jsunit, it shouldn’t be hard to test the packed version.
Eliminating Tedium
Because typing these commands over and over can be tedious, you’ll probably want to create a script to run the
packing commands. This .bat file will compress every .js file and create .js.packed:
compress_js.bat:
for /F %%F in ('dir /b *.js') do java -jar custom_rhino.jar -c %%F > %%F.packed 2>&1
Of course, you can use a better language like perl or bash to make this suit your needs.
Optimize Javascript Placement
Place your javascript at the end of your HTML file if possible. Notice how Google analytics and other stat
tracking software wants to be right before the closing </body> tag.
This allows the majority of page content (like images, tables, text) to be loaded and rendered first. The user sees
content loading, so the page looks responsive. At this point, the heavy javascripts can begin loading near the end.
I used to have all my javascript crammed into the <head> section, but this was unnecessary. Only core files that
are absolutely needed in the beginning of the page load should be there. The rest, like cool menu effects,
transitions, etc. can be loaded later. You want the page to appear responsive (i.e., something is loading) up front.
Load Javascript On-Demand
An AJAX pattern is to load javascript dynamically, or when the user runs a feature that requires your script.
You can load an arbitrary javascript file
from any domain using the following import function:
function $import(src){
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src',src);
scriptElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}
// import with a random query parameter to avoid caching
function $importNoCache(src){
var ms = new Date().getTime().toString();
var seed = "?" + ms;
$import(src + seed);
}
The function $import(‘http://example.com/myfile.js’) will add an element to the head of your document, just like
including the file directly. The $importNoCache version adds a timestamp to the request to force your browser to
get a new copy.
To test whether a file has fully loaded, you can do something like
if (myfunction){
// loaded
}
else{ // not loaded yet
$import('http://www.example.com/myfile.js');
}
There is an AJAX version as well but I prefer this one because it is simpler and works for files in any domain.
Delay Your Javascript
Rather than loading your javascript on-demand (which can cause a gap), load your script in the background,
after a delay. Use something like
var delay = 5;
setTimeout("loadExtraFiles();", delay * 1000);
This will call loadExtraFiles() after 5 seconds, which should load the files you need (using $import). You can even
have a function at the end of these imported files that does whatever initialization is needed (or calls an existing
function to do the initialization).
The benefit of this is that you still get a fast initial page load, and users don’t have a pause when they want to use
advanced features.
In the case of InstaCalc, there are heavy charting libraries that aren’t used that often. I’m currently testing a method
to delay chart loading by a few seconds while the core functionality remains available from the beginning. You may
need to refactor your code to deal with delayed loading of components. Some ideas are to use SetTimeout to poll
the loading status periodically, or having a function called at the end of your included script to tell the main program
the script has been loaded.
Cache Your Files
Another approach is to explicitly set the browser’s cache expiration. In order to do this, you’ll need access to PHP
so you can send back certain headers.
Rename myfile.js to myfile.js.php and add the following lines to the top:
<?php
header("Content-type: text/javascript; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 3;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
?>
In this case, the cache will expire in (60 * 60 * 24 * 3) seconds or 3 days. Be careful with using this for your own
files, especially if they are under development. I’d suggest caching library files that you won’t change often.
If you accidentally cache something for too long, you can use the $importNoCache trick to add a datestamp like
“myfile.js?123456″ to your request (which is ignored). Because the filename is different, the browser will request a
new version.
Setting the browser cache doesn’t speed up the initial download, but can help if your site references the same files
/> on multiple pages, or for repeat visitors.
Combine Your Files
A great method I initially forgot is merging several javascript files into one. Your browser can only have so many
connections to a website open at a time — given the overhead to set up each connection, it makes sense to
combine several small scripts into a larger one.
But you don’t have to combine files manually! Use a script to merge the files — check out part 2 for an example
script to do this. Giant files are difficult to edit – it’s nice to break your library into smaller components that can be
combined later, just like you break up a C program into smaller modules.
Should I Gzip It?
Probably not. Although some browsers can accept compressed javascript (myfile.js.gz) or files returned with the
“gzip” encoding header, this behavior is not consistent between browsers and can be problematic.
If you’re an expert, feel free to experiment, but for the majority of us I don’t think it’s worth the effort or potential
headache.
All done? Keep learning.
Once you’ve performed the techniques above, recheck your page size using the tools above to see the
before-and-after difference.
I’m not an expert on these methods — I’m learning as I go. Here are some additional references to dive in deeper:
zahnarzt | zeitarbeit | buchhandlung | bekleidung | apotheke |
aerobic | paketshop | marketing tool | marketing tools | SEO Blog
—
JavaScripts Guides: Beginner, Advanced
JavaScripts Tutorials: Beginner, Advanced
Google Chart Test Live
Sample Zembly Rss Feed
India Photos in 3D carousel
Enabling JavaScript in Your Browser
Enabling JavaScript in Internet Explorer
To enable JavaScript in Internet Explorer:
- Select Tools > Internet Options… from the menu bar.
The Internet Options dialog box opens.
- Click the Security tab.
- Select the Trusted sites icon in the box of Web content zones.
- Click the Custom level… button.
The Security Settings dialog box opens.
- Scroll down to the Scripting section, and then select the Enable radio button as the option for active scripting.
- Click the OK button to dismiss the Security Settings dialog box.
A Warning message box asks if you are sure you want to change the security settings.
- Click the Yes button to dismiss the message box.
- Click the OK button to dismiss the Internet Options dialog box.
Enabling JavaScript in FireFox
To enable JavaScript in Firefox.
- Select Tools > Options… from the menu bar.
The Options dialog box opens.
- Select the Content icon at the top of the dialog box.
- Select the Enable JavaScript checkbox.
- Click the OK button.
COmpare DOJO, MOCHI KIT, MOO Tools,Yahoo! UI,Prototype and JQuery
JQuery is the BEST
Dojo
—-
- Built in functionality / Power / ease of use — many compatibility issues, ease of use — not good
- add ons / widgets — simple — no widgets
- Size of footprint —23KB
- Documentation / Community — community supported by many companies like IBM, AOL, Sun
Documentation– not good
Mochikit
—
- Built in functionality / Power / ease of use — compatibility good, ease of use — good
- add ons / widgets — not so many , no widgets
- Size of footprint —111KB
- Documentation / Community — Documentation good, still a little community
MooTools
- Built in functionality / Power / ease of use — good
- add ons / widgets — good
- Size of footprint —43KB
- Documentation / Community — had some good community
Documentation — good
Yahoo! UI
- Built in functionality / Power / ease of use — ease of use — some restrictions to use its functions and more time need to learn the functions
- add ons / widgets — ok
- Documentation / Community –
Community good
Documentation–Very good docs
Some bugs have to be fixed some compatibility issues
Prototype
- Built in functionality / Power / ease of use
- add ons / widgets — ok
- Size of footprint —122KB
- Documentation / Community
Had some community
Documentation–Very good docs
ease of use — some restrictions to use its functions and more time need to learn the functions
Compatibility fine
Design is not good
tyle='font-size:12pt;'>Prototype does not provide any widgets or controls
JQuery
- Built in functionality / Power / ease of use
- add ons / widgets — good widgets from jquery UI
- Size of footprint —26.5 KB
- Documentation / Community
had lot of communities behind
Documentation–Very good docs
Ease of use — very good, performance is better that all the other tools
Ease to read and simplified code
Compatibility good except Konqueror
jQuery was the first toolkit to support chaining and that it executes it nicely.
Commnets over comparition
http://programming.reddit.com/info/61xbz/comments
http://mootools.net/slickspeed/
Selectors Prototype 1.6 MooTools 1.2 beta1 JQuery 1.21
IE 6.0 final time (less is better) 2098 1477 1239
mozilla 1.5 final time (less is better) 299 346 935
From the above results we can see that for IE jquery is better
For prototype some tags are not working
http://www.malsup.com/jquery/form/comp/
This url checks JQuery,Dojo,Yahoo! UI,Prototype,Mochikit
From the above url we can see that Jquery supports all the features
jQuery.noConflict
Using jQuery with Other Libraries
From jQuery JavaScript Library
Jump to: navigation, search
[edit]
General
The jQuery library, and virtually all of its plugins are constrained
within the jQuery namespace. As a general rule, “global” objects are
stored inside the jQuery namespace as well, so you shouldn’t get a clash
between jQuery and any other library (like Prototype, MooTools, or YUI).
That said, there is one caveat: By default, jQuery uses “$” as a shortcut
for “jQuery”
[edit]
Overriding the $-function
However, you can override that default by calling jQuery.noConflict() at
any point after jQuery and the other library have both loaded. For
example:
<html>
<head>
<script src=”prototype.js”></script>
<script src=”jquery.js”></script>
<script>
jQuery.noConflict();
// Use jQuery via jQuery(…)
jQuery(document).ready(function(){
jQuery(“div”).hide();
});
// Use Prototype with $(…), etc.
$(‘someid’).style.display = ‘none’;
</script>
</head>
<body></body>
</html>
This will revert $ back to its original library. You’ll still be able to
use “jQuery” in the rest of your application.
Additionally, there’s another option. If you want to make sure that jQuery
won’t conflict with another library – but you want the benefit of a short
name, you could do something like this:
<html>
<head>
<script src=”prototype.js”></script>
<script src=”jquery.js”></script>
<script>
var $j = jQuery.noConflict();
// Use jQuery via $j(…)
$j(document).ready(function(){
$j(“div”).hide();
});
// Use Prototype with $(…), etc.
$(‘someid’).style.display = ‘none’;
</script>
</head>
<body></body>
</html>
You can define your own alternate names (e.g. jq, $J, awesomeQuery -
anything you want).
Finally, if you don’t want to define another alternative to the jQuery
name (you really like to use $ and don’t care about using another
library’s $ method), then there’s still another solution for you. This is
most frequently used in the case where you still want the benefits of
really short jQuery code, but don’t want to cause conflicts with other
libraries.
<html>
<head>
<script src=”prototype.js”></script>
<script src=”jquery.js”></script>
<script>
jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function($){
// Do jQuery stuff using $
$(“div”).hide();
});
// Use Prototype with $(…), etc.
$(‘someid’).style.display = ‘none’;
</script>
</head>
<body></body>
</html>
This is probably the ideal solution for most of your code, considering
that there’ll be less code that you’ll have to change, in order to achieve
complete compatibility.
Also see: Custom Alias
[edit]
Referencing Magic – Shortcuts for jQuery
If you don’t like typing the full “jQuery” all the time, there are some
alternative shortcuts:
* Reassign jQuery to another shortcut
o var $j = jQuery;
o (This might be the best approach if you wish to use different
libraries)
* Use the following technique, which allows you to use $ inside of a
block of code without permanently overwriting $:
o (function($) { /* some code that uses $ */ })(jQuery)
o Note: If you use this technique, you will not be able to use
Prototype methods inside this capsuled function that expect $ to
be Prototype’s $, so you’re making a choice to use only jQuery
in that block.
* Use the argument to the DOM ready event:
o jQuery(function($) { /* some code that uses $ */ });
o Note: Again, inside that block you can’t use Prototype methods
Using the window.open method ? 3 methods to open window
Using the window.open method — 3 methods to open window
Using the window.open method
The syntax of the window.open method is given below:
open (URL, windowName[, windowFeatures])
URL
The URL of the page to open in the new window. This argument could be blank.
windowName
A name to be given to the new window. The name can be used to refer this window again.
windowFeatures
A string that determines the various window features to be included in the popup window (like status bar, address bar etc)
The following code opens a new browser window with standard features.
window.open ("http://www.javascript-coder.com","mywindow");
Note: The popups created using ‘window.open()’ can get blocked by popup blockers.
Click here to find out how to create popups that does not get blocked.
Changing the features of the Popup
You can control the features of the popup using the last argument to the window.open method. The following code opens a window with a status bar and no extra features.window.open ("http://www.javascript-coder.com","mywindow","status=1");
The code below opens a window with toolbar and status bar.window.open ("http://www.javascript-coder.com","mywindow","status=1,toolbar=1");
The table shows the features and the string tokens you can use:
|
status |
The status bar at the bottom of the window. |
|
toolbar |
The standard browser toolbar, with buttons such as Back and Forward. |
|
location |
The Location entry field where you enter the URL. |
|
menubar |
The menu bar of the window |
|
directories |
The standard browser directory buttons, such as What’s New and What’s Cool |
|
resizable |
Allow/Disallow the user to resize the window. |
|
scrollbars |
Enable the scrollbars if the document is bigger than the window |
|
height |
Specifies the height of the window in pixels. (example: height=’350′) |
|
width |
Specifies the width of the window in pixels. |
Examples
The following code opens a window with menu bar. The window is resizable and is having 350 pixels width and 250 pixels height.window.open ("http://www.javascript-coder.com","mywindow","menubar=1,resizable=1,width=350,height=250");
Example 1
A window with location bar, status bar, scroll bar and of size 100 X 100window.open ("http://www.javascript-coder.com","mywindow","location=1,status=1,scrollbars=1,width=100,height=100");
Example 2
Moving the window to a desired location
You can use the window.moveTo function to move the popup window to a desired location.
The code below shows positioning the popup at a desired location
function mypopup(){mywindow = window.open ("http://www.javascript-coder.com","mywindow","location=1,status=1,scrollbars=1,width=100,height=100");mywindow.moveTo(0,0);}
The code positions the popup on the top left corner of the screen.
Putting it all together
Now we will combine all these information to create the popup windows of different types.
The Code below opens a popup window when you enter the page:
<html><head><title>JavaScript Popup Example 3</title></head><SCRIPT language="JavaScript1.2">function poponload(){testwindow= window.open ("", "mywindow","location=1,status=1,scrollbars=1,width=100,height=100");testwindow.moveTo(0,0);}</SCRIPT><body onload="javascript: poponload()"><H1>JavaScript Popup Example 3</H1></body></html>
Notice that the URL is kept blank. This will open a blank window. You can see the code in work in this file:
JavaScript Popup Example 3
Popup On Exit
The following code pops up a window when the user exits a page.
<html><head><title>JavaScript Popup Example 3</title></head> <SCRIPT language="JavaScript1.2">function exitpop(){my_window= window.open ("","mywindow1","status=1,width=350,height=150");my_window.document.write('<H1>Popup Test!</H1>');}</SCRIPT><body onunload="javascript: exitpop()" ><H1>JavaScript Popup Example 4</H1></body></html>
The code contains an extra line:my_window.document.write('<H1>Popup Test!</H1>')
This code displays a line ‘Popup Test!’ in the popup.
The code is available in the file:
JavaScript Popup Example 4
The next page shows you how to close a popup window





