When a user add the markers on the Google Map, I'm saving it as a JSON string on my MySQL database like this:
[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]
"k" is the latitude and "B" the longitude of the added marker.
I also save the polylines between the markers like this:
[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]
I have a function witch fetch all the markers and polylines from the database, to display it back to the screen, here is my query:
function getMarkersByTripId($tripId)
{
if ($bdd = mysqli_connect(_BDD_HOST_, _BDD_USERNAME_, _BDD_PASSWORD_, _BDD_NAME_)) {
$sql = 'SELECT DISTINCT `markers`, `polylines` FROM `trip` WHERE `trip_id` = "'.$tripId.'"';
$req = mysqli_query($bdd, $sql);
if ($req) {
while ($row = mysqli_fetch_row($req)) {
$jsonData= array('markers'=>$row[0], 'polylines'=>$row[1]);
}
echo json_encode($jsonData);
}
else {
echo json_encode(array('status' => 'failure'));
}
}
if ($bdd) {
mysqli_close($bdd);
}
}
a var_dump of $jsonData looks like this:
array(2) {
["markers"]=>
string(79) "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]"
["polylines"]=>
string(63) "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
}
In my JavaScript, when I'm doing:
console.log(jsonText);
It's formed like:
"{"markers":"[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]","polylines":"[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"}"
As you can see, it's a simple string containing the JSON result returned by the function getMarkerByTripId() function. Now, I want to convert my JSON string to an object like this:
var jsonData = JSON.parse(jsonText);
console.log(jsonData);
It seems working and it display something like:
Object { markers: "[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]", polylines: "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]" }
The problem is: I can't access to the latitude/longitude (k/D JSON elements), it's always undefined, here is how I'm doing it after the JSON.parse(jsontext):
console.log(jsonData['markers'].k);
It always return "undefined" and in order to add the marker on the Google map, I need to know what I'm doing wrong with the JSON parsing. The rest is OK, I know how to loop through my JSON object to add the markers and the polylines on the map automatically.
I was thinking that when I'm fetching the JSON string from MySQL database, it may add double quote, witch can defect the JSON parsing. Thank you very much if someone can guide me to the right answer.
jsonData.markers is double json encoded you will first parse jsonData.markers key object
var jsonText = {
"markers": "[{\"k\":52.908902047770255,\"D\":-3.427734375},{\"k\":56.31653672211301,\"D\":7.03125}]",
"polylines": "[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]"
};
var markers = JSON.parse(jsonText.markers);
var polylines = JSON.parse(jsonText.polylines);
console.log('markers ', markers, ' polylines', polylines);
In php code: warp markers, polylines with json_decode() function in while loop, because both values are already json string, and when you use again json_encode these double encode.
while ($row = mysqli_fetch_row($req)) {
$jsonData= array(
'markers'=>json_decode($row[0]),
'polylines'=>json_decode($row[1])
);
}
UPDATE PHP CODE
<?php
$arr1 = array(
"markers" => '[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]',
"polylines" =>'[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]'
);
echo "//your problem \n";
echo json_encode($arr1);
$arr2 = array(
"markers" => json_decode('[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]'),
"polylines" =>json_decode('[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]')
);
echo "\n\n//my solution\n";
echo json_encode($arr2);
//after solution markers, polylines keys wrapped with one more array so you will need to use `[0]` index in javascript
// jsonText.markers[0].k; jsonText.markers[0].d etc
// you can also do
$arr3 = array(
"markers" => array_shift(json_decode('[{"k":52.908902047770255,"D":-3.427734375},{"k":56.31653672211301,"D":7.03125}]')),
"polylines" =>array_shift(json_decode('[[52.908902047770255,-3.427734375],[56.31653672211301,7.03125]]'))
);
echo "\n\n//another one more solution my solution\n";
echo json_encode($arr3);
//now you can access values in JavaScript
// jsonText.markers.k; jsonText.markers.d etc
?>
see more detail click here
The member 'markers' is an array, you must specify from which element you need the coordinates in this array.
Try this for accessing the first one to check if it works :
console.log(jsonData['markers'][0].k);
Related
I try to display data in angularjs via json data array but can't figure out or fix the issue when i return the json data from my php file it give me result
["{name:'abc', age:19}","{name:'xyz', age:21}"]
but its not working because in Angular i need data in format something like this
[{name:'abc', age:19},{name:'xyz', age:21}]
now issue is i can't figure out how can i rearrange this array format i tried JSON.parse() but its not working
its my php code
if($xml->product) {
foreach ($xml->product as $node ){
$productName = $node->name;
$productID = $node->productID;
$productPrice = $node->price;
$productURL = $node->imageURL;
$productCat = $node->categories->category;
//$product = "{name: '".$productName."', productid: '".$productID."' }";
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");
array_push($data1, $product);
}} else {
echo "error!"; } print json_encode($data1);
problem fixed actually i am passing string in array and then encode with json it give me this double quote issue. now what i fix is change string in array and passed by json it automatically convert these array in object :)
its fixed by changing string into array
$product = "{name: '".$productName."', productid: '".$productID."' }";
replace with this
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");
i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`
I have a number of coordinates stored in a sqlite database. I need these coordinates to be used in a heatmap on leaflet.
I'm using the following plugin: https://github.com/Leaflet/Leaflet.heat
The data needs to be in the following format:
var addressPoints = [
[52.344161, 4.912279],
[52.342425, 4.913038],
[52.342034, 4.913256],
[52.341987, 4.912462]];
I extract the data from the sqlite database in PHP using:
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
while ($row = $results->fetchArray()) {
echo json_encode($row['coord']);
}
$db->close();
The data retrieved looks like:
"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"
How can I get the SQLite data inserted in 'var addressPoints' in a correct manner?
Thansk in advance,
JWB
If the data follows that same format with the quotes at start and end and double quotes in between pairs the following should produce an array with the pair as an entry.
$data='"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"';
$pairs=explode('""',trim($data,'"'));
print_r($pairs);
output:
Array
(
[0] => 52.344161000, 4.912279000
[1] => 52.342425000, 4.913038200
[2] => 52.342034000, 4.913256000
[3] => 52.341987000, 4.912462000
[4] => 52.342336000, 4.912106000
)
You could alter your initial php however which would produce different data
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
$json=array();
while( $row = $results->fetchArray() ) {
$json[]=$row['coord'];
}
$db->close();
$json=json_encode( $json );
echo $json;
if you needed this without the quotes around the values...
$json=str_replace('"','',$json);
in the javascript then you could do:
echo "var addressPoints={$json};";
I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;
var labels = new Array();
<?php foreach($crud_data as $cd ) { ?>
labels['<?php echo $cd['name'] ; ?>'] = '<?php echo $cd['label'] ; ?>';
<?php } ?>
$.post('url.php' , { labels:labels} );
Why can I not send labels array like this? It doesn't show anything in Firebug.
My console.log(labels) result:
[]
avatar
"avatar"
email
"email"
id
"id"
name
"name"
password
"password"
if i populate array like this
<?php foreach($crud_data as $cd ) { ?>
labels.push('<?php echo $cd['label'] ; ?>');
<?php } ?>
$.post('url.php' , { labels:labels} );
it works fine !
Oh I see now. If you have string keys, you have to use an object, not an array:
var labels = {};
Arrays in JavaScript are supposed to only hold elements with numeric keys. While you can assign arbitrary properties to arrays, they are not considered to be elements of the array and thus ignored by most processes which deal with arrays.
Additionally you might want to have a look at jQuery.param to see how jQuery will convert the input to a transport-able string and adjust your data structure accordingly.
labels['<?php echo $cd['name'] ; ?>'] =
It seems you want to create an associative array, which is in fact an object in JavaScript (JavaScript has no dedicated associative arrays). So the array itself is in fact empty because you are adding properties to the array object.