Creating a javascript array with PHP json_encode

Posted on 2008-01-28
Medium Priority
Last Modified: 2009-06-17
Anyone have any idea why this would come up as undefined?

		$patients = array(
			    		   'fn' => 'Bobby',
			               'ln' => 'Jones'
		echo '<script type="text/javascript">var patients = (' .  json_encode($patients)  . '); alert(patients.length);</script>';

Open in new window

Question by:stevefNYC
  • 2
LVL 17

Accepted Solution

nplib earned 1000 total points
ID: 20762845
javascript is client side programming,

PHP is server side.

you can't mix them.

you can't define an array in php and call it in javascript.

just doesn't work that way.
LVL 82

Expert Comment

ID: 20762892
because json_encode is returning an object:

Only indexed arrays have a length property. Even it returned an associative array, it would still alert undefined
LVL 82

Assisted Solution

hielo earned 1000 total points
ID: 20762918
>>Even if it were to return an associative array, it would still alert undefined
Well, "undefined" if declared with an Object constructor:
var x = new Object(); // or var x = {}
x['firstname'] = "john";
alert(x.length); // ==> undefined

Zero if used with an array constructor
var x = new Array(); // or var x = []
x['firstname'] = "john";
alert(x.length); // ==> 0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to implement server side field validation and display customized error messages to the client.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.
Suggested Courses

599 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question