Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best do I implement mysql data into a line of javascript code?

I am modifying some javascript for Google maps so that the different pin information is retrieved from my database. If I was to do this with just php it would be like this:

<?php while($row = mysql_fetch_assoc($query))
{$title = $row['title']; $desc = $row['desc']; echo 'This '.$title .' and this '. $desc .';}?>

If there were 5 rows in the database there will be five lines with 5 different titles and descriptions. But I have this line of javascript that I would like to be in a while loop:

map.addMarkerByLatLng(37.8685, -1.5108, "Sanatario de Terburculosos", createInfo("title goes here",""));

How can i write it so that that javascript is in a php while loop or how can i do the javascript equivelant of the php while loop so that i can retrieve multiple rows of lang,lat info each in its own javascript code like above?

Thank you.

like image 378
crmepham Avatar asked Mar 16 '26 21:03

crmepham


1 Answers

ajax.php

<?php
    $obj = array();
    while($row = mysql_fetch_assoc($query)){
        $obj[] = new array(
            "title" => $row["title"],
            "desc"  => $row["desc"],
            "lat"   => $row["lat"],
            "lon"   => $row["lon"]
        );
    }
    echo json_encode($obj);
?>

jquery ajax

$.getJSON("ajax.php",function(data){
    for(var i=0;i<data.length;i++){
        map.addMarkerByLatLng(
            data[i].lon, 
            data[i].lat, 
            data[i].description, 
            createInfo(data[i].title,""));
    }
});
like image 56
Ilia Choly Avatar answered Mar 19 '26 11:03

Ilia Choly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!