How to use JSON from db/php in JavaScript

javascript, jquery

Solution

If you are just going to directly insert your JSON data into a javascript variable (rather than using AJAX), then you shouldn't need a `getJSON` call at all. Just write the object directly like this.

var js_object = <?php echo $mapData; ?>;
alert(js_object.countries.AL);
alert(js_object.countries.GB);

Note that the PHP string is not echoed into enclosing quotes, this means you are directly creating a javascript object literal, not a string that then needs to be parsed into an object via `JSON.parse()`

Problem

I'm using a map plugin to render some data. The data comes from the DB and into a json file - the script works great. I decided to use the data directly from the php output instead of making a json file. For some reason the javaScript doesn't accept the direct php input. I'm using codeigniter MVC Here is the sample code that currently works: ``` $.getJSON('_data/index/data.json', function(data){ ... ``` Here is what I tried: ``` var dataMap = '<? print $mapData;?>'; $.getJSON(dataMap, function(data){... ``` * EDIT 2 * Based on the answers - this option doesn't work either. ``` var dataMap = '<?php echo $mapData;?>'; $.get(dataMap, function(data){... ``` And here is the json data ``` {"countries":{"AL":"1","GB":"1","RS":"1","BG":"6","CA":"3","AT":"2","CD":"1"}} ``` EDIT $mapData is ``` FOREACH LOOP $retdata['countries'][] = strtoupper($row->code); $retdata['num'][] = $row->num; ENDFOREACH LOOP $retdata['countries'] = array_combine($retdat['code'], $retdata['num']); $retdata = json_encode($retdata); ``` And then it is printed into a file as normal. This is into the model, then I pass it to the controller and then into the view. The string is the same in the `$dataMap` that I have on file and the one that is being sent to the view.

Original source