Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSON from db/php in JavaScript

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.

like image 224
Ando Avatar asked Dec 03 '12 19:12

Ando


3 Answers

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()

like image 176
Mike Brant Avatar answered Sep 18 '22 19:09

Mike Brant


Following on from your updated code, it looks like you don't need to call getJSON at all as you already have json data.

Simply take <? echo $mapData;?> and assign it to a variable in your javascript code and use it directly.

like image 22
peacemaker Avatar answered Sep 18 '22 19:09

peacemaker


Just use dataMap as a JSON directly.

alert(dataMap.countries.AL); //output: 1
like image 25
Matheus Azevedo Avatar answered Sep 18 '22 19:09

Matheus Azevedo