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.

<?php

/* set out document type to text/javascript instead of text/html */
header("Content-type: text/javascript");

/* our multidimentional php array to pass back to javascript via ajax */
$arr = array(
	array(
		"first_name" => "Darian",
		"last_name" => "Brown",
		"age" => "28",
		"email" => "darianbr@example.com"
	),
	array(
		"first_name" => "John",
		"last_name" => "Doe",
		"age" => "47",
		"email" => "john_doe@example.com"
	)
);

/* 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"}] */
echo json_encode($arr);

?>

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.

<html>
<head>
	<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>

	<!-- this UL will be populated with the data from the php array -->
	<ul></ul>

	<script type='text/javascript'>
	$(document).ready(function(){
		/* call the php that has the php array which is json_encoded */
		$.getJSON('json_encoded_array.php', function(data) {
			/* data will hold the php array as a javascript object */
			$.each(data, function(key, val) {
				$('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
			});
		});

	});
	</script>

</body>
</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.

$.getJSON('json_encoded_array.php', {name:'Darian Brown',age:40}, function(data) {
	// ... handle response as above
}