Getting database values in Javascript variable dynamically - javascript

I researched this subject many times but I could not find the right answer to my question. Let me explain it.
I'm creating an app with the Google Maps API where I want to have multiple locations shown on the map, based on my database values. I'm having an object called Locations in my javascript, where I store the the variables 'name', 'lat' and 'lon' (latitude, longtitude).
var Locations =
[{
name: 'test',
lat: 52.351753,
lon: 5.002035
},
{
name: 'test2',
lat: 52.390839,
lon: 4.908722
}];
This part is where I store my locations. Although this is working, it is hardcoded.
So, I want to get all my mysql database values out of the database into my javascript variable dynamically. I foreach'd through the database entry's with PHP:
foreach ($query as $post)
{
?> <h1><?php echo $post['naam'] ?></h1>
<p><?php echo $post['plaats'] ?></p>
<p><?php echo $post['categorie'] ?></p>
<?php
}
Now I tried to get all of those values and put them into my javascript variable, but without any succes.
var bedrijven = <?php echo json_encode($post); ?>;
When I console.log 'bedrijven' i'm only getting the last entry, but I want every row stored. Can someone help me with this? Would be really cool if it worked.
I hope I explained well enough.
Thanks!

$post is your iteration variable, so it only contains one element of the array at a time. If you want the entire array, assign that:
var bedrijven = <?php echo json_encode($query); ?>;

Try:
PHP:
function getMarkers(){
$response = array();
foreach ($query as $post) {
$response[] = array(
'name' => $post['naam'],
'lat' => $post['plaats'],
'lng' => $post['categorie'],
);
}
echo json_encode($response);
}
then JS:
function addMarkers(json){
var title =json[index]["naam"];
var lat =json[index]["plaats"];
var lng =json[index]["categorie"];
marker = new google.maps.Marker({
position: new google.maps.LatLng (lat, lng),
map: YOUR_MAP
});
}
jQuery.getJSON("URL OF PAGE",{
format: "json",
dataType: 'json',
contentType: "application/json; charset=utf-8"},
function(json){addMarkers(json);
});
better, to send the info with json and retrieve it with jQuery's getJSON, this may need some tweaking.. But I have created what your talking about. Shout if any further help is required.
You May have to look into this a tiny bit to configure it..
GOOD LUCK!

The examples on http://us1.php.net/json_encode should be helpful. It looks like your $post should be an associative array:
$post[] = ("name"=>"test","lat"=>52.351753, "lon"=> 5.002035); ?>
var bedrijven = <?php echo json_encode($post); ?>;
outputs:
var bedrijven = [{"name":"test","lat":52.351753,"lon":5.002035}];

Related

send php array through jquery ajax with index and recieve the array value

i am working on online exam test where childArray[] contains data from each row of table and parrentArray[] contains number of childArray[]. i want to get value of each childArray from ParentArray with Index passed through ajax.
<?php
$childArray1[]=[1,question,optionA,optionB,optionC];
$childArray2[]=[1,question,optionA,optionB,optionC];
$parentArray[]=[$childArray1,$childArray2];
?>
<script>
$(document).ready(function(){
var counter=0;
$("#ButtonNext").click(function(){
$.ajax({
type:"POST",
url: "ChangeQuestionProcess.php",
data:{
MainList:"<?php echo json_encode($parentArray); ?>",
Counter:counter,
},
success: function(result){
$("#callMe").html(result);
}});
counter++;
});
});
</script>
ChangeQuestionProcess.php
<?php
$index=$_POST["Counter"];
$test[]=$_POST["MainList"];
echo test[$index];
?>
In your ChangeQuestionProcess.php, this line:
$test[]=$_POST["MainList"];
...is saying "take the contents of $_POST["MainList"] and make it the next element of the array $test"
You're doing a similar thing at the top of your first script - I think you mean this, without the [] after the variable names:
<?php
$childArray1=[1,'Question 1','Option 1A','option 1B','option 1C'];
$childArray2=[2,'Question 2','Option 2A','option 2B','option 2C'];
$parentArray=[$childArray1,$childArray2];
?>
You could even simplify this to:
<?php
$parentArray = [
[1,'Question 1','Option 1A','option 1B','option 1C'],
[2,'Question 2','Option 2A','option 2B','option 2C']
];
?>
Now back to ChangeQuestionProcess.php again - bear in mind that $_POST["MainList"] is going to be a string containing JSON-encoded data (as that's what json_encode() returns)
Therefore what I think you are trying to do is read the array of JSON-decoded data into $test, which you would do like so:
$test = json_decode( $_POST["MainList"] );
Finally, you're missing a $ when echoing your variable. But as $test[$index] is an array, you'll just see Array on your screen instead of its contents. I think you need something like print_r instead of echo:
<?php
$index = $_POST["Counter"];
$test = json_decode( $_POST["MainList"] );
print_r( $test[$index] );
?>

Passing data from PHP array to Highcharts chart with JSON

I am trying to draw a highcharts chart that comes from my sql database which i am querying with getdata.php?id=allTemp. I don't really know about JSON that much but I have assembled the code below so far, and the chart does not even draw. the $.getJSON function works when I get a single variable such as weather.wesleyweisenberger.com/getdata.php?id=humidity, but as soon as I try to fetch getdata.php?id=allTemp it does not work, please help me...
while($data = $result->fetch_assoc()){
echo json_encode($data, JSON_FORCE_OBJECT);
}
and the return is in the format
{"timestamp":"2018-05-30 00:33:05","temperature":"67.39","humidity":"66.57","pressure":"99.21"}{"timestamp":"2018-05-30 00:47:39","temperature":"65.52","humidity":"70.41","pressure":"99.2"}{...
My index.php file reads:
<script>
$(function(){
$.getJSON('getdata.php?id=allTemp', function(json){
$('#container').highcharts({
series: [{
data: json
}],
title: {
text: 'Title'
}
})
})
})
</script>
<div id="container" style="width:100%; height:400px;"></div>
{...}{...}{...}
That is an invalid json pattern. You are getting this because you are echoing multiple json objects, where the responses expects a single one. You can correct this by only echoing once.
$results = array();
while($data = $result->fetch_assoc()){
array_push($results, $data);
}
echo json_encode($results);
The Highchart uses arrays to fill its data, and you are just returning a lot of objects side by side, with no actual acceptable format, now with the code bellow, you will print an array of objects stringified.
Try this on your PHP:
var $stringToReturn = [];
while($data = $result->fetch_assoc()){
push($stringToReturn, $data);
}
echo json_encode($stringToReturn);

How to insert a PHP 'while loop' into JavaScript code?

I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>

How to pass variables from while loop of PHP to JavaScript?

I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}

php/mysql write array to json file

I have the following issue, my php code gets the required data from the dB:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
As you see this writes to a json file - results:
{"0":{"nmech":"2.00","nelect":"2.00","nplant":"2.00","ncivil":"2.00"}}
When I use the following js code to extract from json file:
$.getJSON('newport.json', function(data) {
console.log(data);
The console log using chrome displays the following:
[Object]
0: Object
nmech: "3.00"
__proto__: Object
length: 1
only shows the first key/value pair and not all 4 K/V pair? Can someone explain what I am doing wrong please.
Writing the results to a json file is overkill, IMHO. Why not just add the json into a Template or Page view (PHP).
<script>
// Create settings from PHP/Session and
// Initialize Registration Namespace
var registrationSettings = <?php echo (!empty($data)) ? #json_encode($data) : json_encode(array()); ?>;
Registration.init({ settings: window.registrationSettings });
</script>
Obviously, you don't have a Registration namespace object, but this just an example approach to setting settings from PHP when the page first loads.
All you really need it to output some data.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : json_encode(array()); ?>;
</script>
Or maybe a more simple way to write it would be.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : '[]'; ?>;
</script>
I can see your trying to file (or cache) the results. You should probably just write an AJAX method in your PHP controller to handle the request. The data could be cached server side in Memcached or some other fast handler of data. Most PHP frameworks support memcached.
This is ok, because your PHP array looks like this:
<?php
$arr = [
[
"key1" => "value1",
"key2" => "value2",
]
]
You must use data[0]['key'] to access key1 part of first element.
Another (better solution) is to not to use while loop in php, since you are expecting 1 element in your case to be returned from mysql. Use like this then:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
//Get first row from db.
$emparray = mysqli_fetch_assoc($result);
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
Now your data will be in javascript like you expected on beginning.

Categories

Resources