Wednesday, November 12, 2014

Pass a PHP Array to Javascript as JSON using AJAX and json_encode

OVERVIEW

You will mostly likely (or already have) reached a point where you have a PHP array and you need to be able to access that array from inside a Javascript function. You may wonder if it is possible to pass an array from PHP to Javascript. Fortunately I have created a tutorial on how this can be achieved. Below I will show you how to Pass a PHP Array to Javascript as JSON using AJAX. There are two parts to accomplish this task.

CREATING THE PHP ARRAY

Firstly you need a PHP script which has the PHP array you want to pass back to Javascript. You encode the array into a JSON string using the PHP function `json_encode()`. We then echo the string into the PHP file to make it accessible to the AJAX function calling this script.

CALL THE PHP SCRIPT THAT CONTAINS THE PHP ARRAY

Secondly we create an HTML which will contain the AJAX function to call the PHP script. We will use the jQuery `$.getJSON` function which converts the output from the PHP function ‘json_encode()’ into a JSON object. Once we have the JSON object, we can loop through it and use it as we require. We don’t really need to convert the JSON array to javascript array since we use jQuery’s ‘$.each()’ function to loop through the JSON array that is returned.

PASS A PHP ARRAY TO JAVASCRIPT AS JSON USING AJAX

Below is the code that is to be placed into the PHP script. This file will be called by the jQuery `$.getJSON` function.
  1. <?php
  2. /* set out document type to text/javascript instead of text/html */
  3. header("Content-type: text/javascript");
  4. /* our multidimentional php array to pass back to javascript via ajax */
  5. $arr = array(
  6.         array(
  7.                 "first_name" => "Darian",
  8.                 "last_name" => "Brown",
  9.                 "age" => "28",
  10.                 "email" => "darianbr@example.com"
  11.         ),
  12.         array(
  13.                 "first_name" => "John",
  14.                 "last_name" => "Doe",
  15.                 "age" => "47",
  16.                 "email" => "john_doe@example.com"
  17.         )
  18. );
  19. /* encode the array as json. this will output [{"first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@example.com"},{"first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com"}] */
  20. echo json_encode($arr);
  21. ?>

JAVASCRIPT / HTML CODE SNIPPET

Place this code into a file with the extension `.html`. The below code will call the above PHP script using AJAX and the jQuery function `$.getJSON`. The PHP script will have the PHP array encoded as a json string. Once the `$.getJSON` function returns, the Javascript function will have access to the PHP array that has been converted into a JSON object.
  1. <html>
  2. <head>
  3.         <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
  4. </head>
  5. <body>
  6.         <!-- this UL will be populated with the data from the php array -->
  7.         <ul></ul>
  8.         <script type='text/javascript'>
  9.         $(document).ready(function(){
  10.                 /* call the php that has the php array which is json_encoded */
  11.                 $.getJSON('json_encoded_array.php', function(data) {
  12.                         /* data will hold the php array as a javascript object */
  13.                         $.each(data, function(key, val) {
  14.                                 $('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
  15.                         });
  16.                 });
  17.         });
  18.         </script>
  19. </body>
  20. </html>

PASSING VARIABLES TO PHP USING JSON AND AJAX

If you would like to pass some variables to PHP you can change the parameters as shown above. In my example below, I pass the variables name and age and then the PHP function could use these to search a database or file for that person and then return that specific information as a JSON array.
  1. $.getJSON('json_encoded_array.php', {name:'Darian Brown',age:40}, function(data) {
  2.         // ... handle response as above
  3. }

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...