PHP pass an Array to Javascript using AJAX (jquery or ExtJs) and PHP’s json_encode

Alright! so this subject has been brought to my attention to write on.

There are many reasons why you will want your PHP arrays to be available at client side. One of the main reason for me is that I want to improve overall user experience when I load lot of data for the user and keep it at client side unless another server call is required. This makes application faster and responsive. But this is not the only use case why we may want PHP arrays on client side there are many others which is depends on what you are trying to achieve.

One simple answer my friend was seeking was whether it is was really possible to get a PHP array at client side. My answer was Yes! Not only can you bring that array to client side but also in a nice OOPS way using JSON.

If you want to know about JSON please visit http://www.json.org

Lets do this step by step.

First we will create a PHP page or in other words a PHP script as shown below. Save it as target.php

Output of above echo will be

Let’s see how we can get this array in ExtJS 4

Check this code snippet to see how we can get the above array using ExtJS

[geshi lang=”javascript” nums=”1″ target=”_self” ]

Above code just outputs jsonobj to Chrome’s console that you can view by pressing CTRL+SHIFT+I and checking under console tab. For the sake of simplicity I’ve include a screenshot below

As you can see a well formed PHP array in our client side Javascript function. Well from here put your thinking cap on and do whatever you want to do with this data. I heard you asking me a question that how the hell do I even get those Object values. Alright! here is how you do it. So as you can see an Array is return which has two objects. We can access it the way we access an object. i.e. like this

var jass_location = obj[0].location;

// so we can access individual object by an index value. In our case 0 and 1 are index values representing two objects returned.

 

Let’s see how we can get this array using jQuery

Check this code snippet out

[geshi lang=”javascript” nums=”1″ target=”_self” ]

If you run the above code snippet you will get exactly the same result as shown in the Picture above. You can access the data same way as I shown you before. But lets go a step further and create a HTML List from the data received from PHP

So change the above to look like this

 

 

You will get a nice HTML list as show below

As you noticed that we used $.each in out jQuery funtion to  iterate through the returned array. You can do the same with Ext.Array.each for Ext example above.

I hope I made any sense If not please feel free to ask a question.

Cheers,

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.