Passing JSON data to JavaScript using PHP.

This is a short tutorial on how to pass JSON data from PHP to JavaScript. This can be useful if you have a PHP array that you need to access with JavaScript. Similarly, you can also use it to pass PHP objects to your JS scripts.

Take a look at the following example:

In the PHP script above, we created an array. Afterwards, we converted this array into a JSON string by using the json_encode function.

The resulting JSON string will look like this:

{“name”:”Lionel Messi”,”team”:”Barcelona”,”dob”:”1987-06-24″}

Now, we will need to pass this string to our JavaScript and convert it into an object:

In the snippet above, we printed out our JSON string inside the JSON.parse() method. As a result, the code that is delivered to the browser will look like this:

Once the page has loaded, the JSON.parse() method will parse our JSON string into an object and assign it to our jsonData variable. If you run the example above and check your browser console, you will see the following output:

JSON data being outputted in Chrome's developer console.

A screenshot of our new JS object.

Now, we can simply access the data like so:

As you can see, it’s pretty straight forward!

Uncaught SyntaxError: Unexpected identifier.

This is an error that you will come across if the JSON data contains special characters such as single quotes.

That, or it might be something like:

Uncaught SyntaxError: missing ) after argument list

To fix this, you will need to inspect your JSON data for any special characters. In my case, I was able to solve this error by using PHP’s addslashes function:

If this does not solve your issue, then I suggest that you run your JSON string through one of those free online JSON validators.

Hopefully, you found this guide useful!

Related: Pass a JS object to a PHP script.

Facebook Comments