i have an sql with 2 columns, latitude and longitude.
I am able to print out the entries of these two columns like:
$result = mysqli_query($con,"SELECT * FROM events");
while ($row = mysqli_fetch_array($result)) {
echo $row['latitude'];
echo $row['longitude'];
}
I also have a JS function, where i need a while to add as many JS lines as the sql query returns. Here is the JS:
var myMarkers = {"markers": [
{"latitude": "47.47256859162068", "longitude":"19.055979251861572", "icon": "marker.png", "baloon_text": 'This is <strong>Budapest</strong>'},
]
};
So i'd need something like: "latitude": $latitude[i] and "longitude": $longitude[i] all these in a for or a while
Is there a way that i could pass the content of the two sql rows to a js function, to be able to get all the line with the correct values?
5 Answers 5
An example of what to do can be seen here.
Convert the data into JSON.
$markers = array();
while ($row = mysqli_fetch_array($result)) {
$markers[] = array(
'longitude' => $row['longitude'],
'latitude' => $row['latitude']
);
}
$markersJson = json_encode($markers);
Then pass it to your JS:
<script type="text/javascript">
var obj = JSON.parse('<?= $markersJson ; ?>');
console.log(obj);
</script>
Check your console to view the structure of the data.
4 Comments
Convert the result of mysql data array into JSON.
$result_json = json_encode($result);
And parse this variable in jQuery fashion to access all values.
<script type="text/javascript">
var obj= $.parseJSON('<?= $result_json; ?>'); //Parse the above encoded Json.
//Here is how you iterate
var json = $.parseJSON(obj);
$(json).each(function(i,val){
console.log(val);
});
</script>
Comments
you can use something like this:
<script>
var myMarkers = {"markers": [
<?php
$result = mysqli_query($con,"SELECT * FROM events");
while ($row = mysqli_fetch_array($result)) {?>
{"latitude": "<?php echo $row['latitude'];?>", "longitude":"<?php echo $row['longitude'];?>", "icon": "marker.png", "baloon_text": 'This is <strong>Budapest</strong>'},
<?php
}
?>
]
};
</script>
PHP is a server side language so it gets executed before javascript which is a client side language, the trick is to use :
"latitude": <?php echo $latitude[i];?>
Comments
you can try
<script>
<?php
$result = mysqli_query($con,"SELECT * FROM events");
$i=0;
while ($row = mysqli_fetch_array($result))
{
?>
var myMarkers[<?php echo $i;?>] = {"markers": [{"latitude": "<?php echo $row['latitude'];?>", "longitude":"<?php echo $row['longitude'];?>", "icon": "marker.png", "baloon_text": 'This is <strong>Budapest</strong>'},]};
<?php
$i+=1;
}
?>
</script>
Comments
Fetch your data through the SQL query and put the output in a single array via your loop.
Use json_encode() to serialise the array into a transportable form, pass it to JavaScript, for example by an XMLHttpRequest and parse it in JS with the internal JSON.parse().
ballon_textcome from? Is it in the same database as lat long?