Using JSON with PHP and JavaScript

When you want to pass data from PHP to JavaScript, or from JavaScript to PHP, JavaScript Object Notation (JSON) is the method of choice. We provide examples that show and explain:

But first we provide a little background information for those who may be unfamiliar with JSON.

What is JSON?

JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript. JSON values can consist of:

  • Objects: collections of name-value pairs
  • Arrays: ordered lists of values
  • Strings in double quotes
  • Numbers
  • True, false, or null.

Although JSON is based on a subset of JavaScript, it is a language-independent text format that makes use of conventions familiar in many programming languages facilitating data interchange among them.[1]

JSON Support in PHP and JavaScript

JSON encode/decode functions have been available in PHP since version 5.2. JavaScript's JSON stringify/parse methods are supported by all current browsers.[2] JSON libraries and/or built-in support are provided for many other programming languages as well.

When passing data from PHP to JavaScript, the PHP json_encode function is used to return a string containing the JSON equivalent of the value passed to it. You can then use the JavaScript JSON.parse method to safely handle the data and make it available in a form usable by JavaScript.

Back to top


  1. Find out more about JSON at json.org, Wikipedia and ECMA. ^
  2. Even Internet Explorer 8 (in standards-compliant mode) supports JSON. A json2.js library providing support for older browsers is available at github ^