Passing PHP Array To JavaScript Using wp_localize_script()

If you are looking for a generic way to pass a PHP variable to JavaScript, please move on.  This post is specific to WordPress plugins.

If you don’t know how to pass a PHP variable to JavaScript for your WordPress plugin, go through this very good post by Otto – Passing parameters from PHP to Javascripts in plugins This is a very safe and straightforward way to pass your PHP variables into your JavaScript.

This works perfectly fine if your variable is NOT an ARRAY.  So, if you want to pass your PHP arrays to your JavaScript, you’ll have to do a bit more, but it is still pretty much straight forward.  Here are the steps –

  1. Encode your PHP array using json_encode()
  2. Pass the encoded array to your JavaScript using wp_localize_script()
  3. Parse the JSON encoded data in JavaScript back to a JSON object

Ain’t it simple?  Let’s take one example. Here’s how my sample PHP array looks like –

$my_arr = array('my array',
'name' => 'Ronak',
'surname' => 'Gandhi',
'phone' => array(
'home' => 12345,
'office' => 67890),
'hobbies' => array(
'photography',
'programming',
'driving'),
);

Now we need to encode this array into JSON string.

$my_json_str = json_encode($my_arr);

json_encode() serialized PHP arrays into strings. If you print the encoded string, it will look like this –

{"0":"my array","name":"Ronak","surname":"Gandhi","phone":{"home":12345,"office":67890},"hobbies":["photography","programming","driving"]}

Now that our array is a PHP string, we can pass it to JavaScript using wp_localize_script().

$params = array(
'my_arr' => $my_json_str,
);

wp_enqueue_script(‘my-java-script’);
wp_localize_script(‘my-java-script’, ‘php_params’, $params);

Next step is to parse the JSON string back to a JSON object in JavaScript. Our PHP array passed using wp_localize_script() is available in JavaScript as php_params.my_arr.  If you check the string value of php_params.my_arr, you will see lot of quot; amp; etc.  So first we need to replace those escaped characters.  If you have other such characters in the string, you’d have to replace them too.

/* Before replacement
{"0":"my array","name":"Ronak","surname":"Gandhi
","phone":{"home":12345,"office":67890},"hobbies":["photography","programming","driving"]}
/
var my_json_str = php_params.my_arr.replace(/"/g, '"');
/
After replacement
{"0":"my array","name":"Ronak","surname":"Gandhi","phone":{"home":12345,"office":67890},"hobbies":["photography","programming","driving"]}
*/

Now we can safely parse this string and convert it into a JSON object.

var my_php_arr = jQuery.parseJSON(my_json_str);

Once this is done, we can access my_php_arr as any other JSON object. Parameters can be accessed as my_php_arr[‘name’], my_php_arr[‘surname’] etc.

Awesome Flickr Gallery Goes Live. Check It Out !!!

Awesome-Flickr-Gallery LogoI was working on a Flickr gallery plugin for WordPress since a week.  I have finally released it now.  The plugin enables you to integrate your Flickr photo-stream with your WordPress enabled website.

Well, you must be thinking there are probably hundreds of such plugins already available then why write one more.  Actually I wasn’t satisfied with any of the current Flickr gallery plugins.  They lacked something or the other I wanted.  Don’t misunderstand me here – all of them are really great in their own way but none fit my needs.  So I decided to write one on my own.  To be honest, I wanted to do some side project to learn something new.  I got to learn PHP, Javascript and SVN.

The plugin now is still has only basic functionality.  I plan to take it to next level where it can compete with other Flickr gallery plugins.  I have created a dedicated page for this project, check it out.

Are You A Fan Of Keyboard Shortcuts? Try Vimperator For Firefox

Do you like to use keyboard shortcuts for faster navigation in applications like editors, browsers, media players, etc?  I use them a lot for navigating through applications like, GMail, Firefox, Movist, Picasa to name a few.  Keyboard shortcuts help a lot in avoiding mouse usage which in turn speeds up the process as you don’t have to stretch out to your mouse or touch-pad every-time you want to do something.  If you fall in this category too then you will love Vimperator. Continue reading “Are You A Fan Of Keyboard Shortcuts? Try Vimperator For Firefox”

Why Did I Choose Pentax K-x Over Canon 500D And Nikon D3100?

I bought my first DSLR 3 weeks back.  And to surprise to a lot of people, it is a Pentax K-x.  I chose to go with Pentax K-x over Nikon D3100 and Canon 500D.  I get asked “WHY Pentax” many times. Well, modern-day cameras are very much advanced and are very capable.  All are so close in terms of IQ that it is difficult to decide on one.  Because of this, we need to consider other aspects of them to come to a conclusion.

So let’s begin –

  • In-body image stabilization – Pentax offers in-body image stabilization that both Canon and Nikon don’t.  Pentax has implemented image stabilization in the camera body by using sensor shift mechanism.  The sensor shifts itself (kind of vibrates) at a very fast rate to compensate with the camera shake induced by shaky hands of the photographer.  Main advantage of in-body image stabilization is – well, it is in body.  So, ANY lens you mount on the camera becomes stabilized by default. In contrast, Canon and Nikon prefer image stabilization in lenses, which makes the lenses bigger and of course expensive.
  • Ergonomics – My Pentax K-x just feels right in my hands.  All the controls are at the right place.  The body is smallest of the lot with just right amount of weight. The Canon was the worst of the lot with the Nikon coming very close to the Pentax.
  • Low light IQ – This is where Pentax scores most.  This has become Pentax’s USP since K-x, K-5 and now K-r.  Pentax takes a conservative approach towards noise reduction to retain details in photos.  This enables us to process the image the way we want. The noise reduction software are getting better and better day by day, so I’d prefer to do it in the computer with all the processing power and intelligence than in camera.
  • Fastest among the lot – The K-x can shoot at 4.7 frames per second.  This is the fastest burst shooting rate among the three cameras.  Though I won’t need such high-speed shooting everyday, it’s a nice to have feature.
  • Backward compatibility with older glass – Pentax has maintained backward compatibility with all old lenses they have ever made.  So I can use ANY Pentax lens EVER made with my K-x.  Some of the prime manual focus lenses are very cheap in second-hand market. Though Canon and Nikon both have a larger set of lenses on offer, Pentax gives me way more choices than I will ever buy.
  • Largest and brightest view-finder
  • Bang for the buck – Have you ever seen a Pentax advertisement on TV or a hoarding on a road?  I haven’t, because Pentax doesn’t spend much on marketing.  They are a very small company focused on R&D behind their products.  This enables them to price their products lower compared to Canon and Nikon.  I bought my K-x along with 18-55mm and 55-300mm lenses for USD 629.  In this amount with Canon I would have only got the body, or with Nikon one kit lens with the body.

One negative point for Pentax is their absence in retail outlets.  Not sure why but Pentax don’t stock enough cameras, lenses and accessories in retail electronic stores.  This keeps prospective customers away from trying a Pentax camera in the store.  They don’t have good service network too in most of the countries.  In India, they don’t have any presence at all. So if this matters to you, you may want to be safe and go with either of Canon or Nikon.

The main point going against the Nikon D3100 was the stripped down body.  Nikon has removed the focus motor from the D3100, so the lens has to have a focus motor to auto focus.  It also doesn’t have the bracketing feature, which is considered very basic and very useful for HDR imaging.  Nikon tends to do such things with their entry-level DLSRs.

The main point going against the Canon was the price and how quickly they obsolete camera bodies.  500D is now 2 generations old camera as 550D is in market since few months now and 600D already been announced.

If I had a little more budget, I would have gone for the Pentax K-r.  It is new and improved K-x with things like –

  • Dedicated AF assist lamp.  It helps the camera in focusing in very low light (no entry-level DSLR has this).
  • Visible focus points in view-finder (most K-x reviews rant about this point)
  • 3 inch LCD with 921k pixels
  • Even higher shooting rate of 6 fps

So there I have it, the Pentax K-x.  Here are some of my favorite shots since I have my new toy.

The Ferocious Cheetah…

Flamingo posing for me…

Lion cubs enjoying their childhood…

An abandoned barn…

A seagull in flight…

Don’t forget to take a look at my Photos Page for more examples. Signing off… Tada…

[schema type=”product” url=”http://en.wikipedia.org/wiki/Pentax_K-x” name=”K-x” description=”The Pentax K-x is a 12.4 megapixel digital single-lens reflex camera, announced on September 16, 2009. Pentax K-x uses an Exmor, Sony-made sensor (different than the back-lit Exmor-R used in other Sony models). In some cases it even approaches the quality produced by full-frame DSLRs like the Nikon D700 and the Canon 5DMkII, both with larger sensors. The Pentax K-x is suitable for low light conditions for both still and video photography.” brand=”Pentax” manfu=”Pentax Ricoh Imaging” ]

Bajaj Allianz Customer Care – Thumbs Down

Bajaj Allianz Insurance company is arguably the best in industry when it comes to customer friendliness and ease of getting/renewing an Insurance. However I became victim of their buggy online renewal and their ill-equipped, ill-trained customer care executives.

It all started the day I recieved an email from Bajaj Allianz notifying me that my two-wheeler insurance is due renewal in a months time. That’s good, I have 30 days to get my insurance renewed before it expires. Never did I know that I’d be making calls to various people to get the task done on the expiry day.

Continue reading “Bajaj Allianz Customer Care – Thumbs Down”

The Samsung “bada” OS Revolution

Makani Gadzair is a smart-phone apps developer.  I found his article very interesting, so posting it here.

[…] Misconceptions of the Samsung Bada platform

The Samsung Bada Revolution

I’ve been reading some news articles by people that don’t really seem to know what they are talking about, by making statements such as:

“Bada, on the other hand, is looking shaky. After an overblown launch at the end of 2009, there’s still only one handset available that runs it — the Samsung S8500 Wave. Still, as it’s been born in-house, the company is rather less likely to unceremoniously dump it in the same way it has Symbian.” – Samsung dumps Symbian

For an article dated October 1st, this guy really doesn’t have its’ facts right.

Firstly, the Bada platform is already launched on two new phones, the Wave 2 and Wave 2 Pro in certain countries and more countries coming soon. They are also launching a third device this month called the Wave 723. In reality, the Bada platform is actually a remarkable success for Samsung. It really is stunning, considering the competition they faced with existing operating systems, including iOS, Android, Symbian, Blackberry and Windows Mobile. Yet they managed to get a million sales in the first 4 weeks, and already at 10 million app downloads. […]

Read complete article here.