How do I pass an array from php to javascript?

There are two questions: 1) how to get what I need from the database. 2)how to transfer what I got from the database to javascript I have an html file. it has javascript map enabled.js and file map.php. java script is normally executed, and the pcp file is not executed like. I do not know how to bind a javascript and a pcp together in an html file. I did not study pcp and javascript, I have a slightly different specialization, but now I have to write something out of necessity.

Here is the code map.php:

 <?php 
        $hostname = "***************"; 
        $username = "****************"; // имя пользователя (в Denwer`е по умолчанию "root")
        $password = "**********"; 
        $dbName = "***********";
        $table = "test_table";
        mysql_connect($hostname, $username, $password) or die ("Не могу создать соединение");
        mysql_select_db($dbName) or die (mysql_error());
        $query = "SELECT coord1,coord2 FROM $table";
        $res = mysql_query($query) or die(mysql_error());
        mysql_close();
?>

Here from the database I need to get an array of elements coordinate 1 and coordinate 2 example of an array element format [54.345324,23.4354353]

Then you need to pass this array to javascript, here it is already initialized, but you need to fill it in from the database. The array is called markers. map.js

var map;
var point = 1;
//точки для двигателя
var markers = {
    point1:[55.755786, 37.617633],
    point2:[55.7543712, 37.6104643],
    point3:[55.7531491, 37.6101551],
    point4:[55.7506212, 37.6101143],
    point5:[55.7541852, 37.5274149],
    point6:[55.7473746, 37.609723],
    point7:[55.803607, 37.328598],
    point8:[55.7422534, 37.6064208],
    point9:[55.7397707, 37.6055861],
    point10:[55.704945, 37.5277036],
};

$(document).ready(function(){
       //карта
    var latlng = new google.maps.LatLng(55.755786, 37.617633);
    var myOptions = {
      zoom: 13,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    //отмечаем все точки на карте
    var marker = [];
    for(i in markers){
        marker[i] = new google.maps.Marker({
            position: new google.maps.LatLng(markers[i][0], markers[i][1]), 
            map: map
        });
    }

    //map.panTo(new google.maps.LatLng(markers.point10[0], markers.point10[1]));

    //двигатель карты по точкам
    function mover(){
        map.panTo(new google.maps.LatLng(markers["point"+point][0], markers["point"+point][1]));
        point ++;
        if(point>10)point=1;
    }

    //карта не используется
    google.maps.event.addListener(map, 'idle', function(){
        setTimeout(mover, 500);//время в милисекундах
    });
    });

P.S. since due to the lack of points, there is no opportunity to either plusanut or answer, I will write here. thank you to the user Inkognitoo,dekameron for help. I got what I wanted to implement. Everything works. I used the idea of decameron.the first or second time I work with pcp. I have been searching for a long time what is the point and why it does not work, it turns out that I had an html file and in it ?> and also

BUT the Deonisa SOLUTION turned out to be better because you don't have to everything is stuffed into the echo, you can use the html page and everything will be neat and clean. indeed, this is not a gavnokod will be.

Http://www.wiseguys.com.ua/ here is a ready-made solution, well, this is only part of what I plan, but it's already good that one piece is ready. I'm not a web developer at all, I work with android OS.

Author: Firespirit, 2013-07-14

3 answers

Mysql_query(); returns not a table, but a handle of the resulting table. In your case - two columns with elements. You can get the values from the descriptor, for example, by using the function mysql_fetch_assoc (); . The array from php to JavaScript is passed through the good old echo. You can read about it here

The code may look something like this: (typed from memory, there may be errors )

$query = "SELECT coord1,coord2 FROM $table";
$res = mysql_query($query) or die(mysql_error());

echo 'var markers = {'; 
while($myrow = mysql_fetch_assoc($res))
  echo "point{++$i}:[{$myrow['coord1']}, {$myrow['coord2']},";
echo '};';
 2
Author: Павел Сотников, 2013-07-14 14:41:45

My answer is more of an addendum/comment to the answer @dekameron.

Everything would be fine, but neither in the first answer, nor in your, nothing is said about ajax. Like, did you leave the vehicle food for thought? ))

PHP

$data = false;
if(mysql_num_rows($res) > 0){
    // если хоть что-то есть, то формируем ответ
    while($myrow = mysql_fetch_assoc($res)){
        $data['point'.(++$i)] = array($myrow['coord1'], $myrow['coord2']);
    }
}
echo json_encode($data); // и ничего дописывать не надо

JS

// отправляем запрос в map.php
$.ajax({
    url:'map.php',
    type:'POST',
    dataType: 'json',
    data: {key:val}, // если надо
    success: function(data){
        if(data){
            console.log(data); // все полученные координаты, именно в том виде, который требовался ТС
        } else {
            // действия в случае, если координаты в БД отсутствуют
        }
    }
});
 2
Author: Deonis, 2013-07-14 16:41:14
$query = "SELECT coord1,coord2 FROM $table";
$res = mysql_query($query) or die(mysql_error());
$data = new stdClass();

while($myrow = mysql_fetch_assoc($res)){
  $key = 'point'.(++$i);
  $data->$key = array($myrow['coord1'], $myrow['coord2']);
}

//В нужном месте:

echo 'var markers = '.json_encode($data).';';

Upd

P.S. When will you stop using mysql_* functions?

P. P. S. stdClass to output curly brackets instead of square brackets when $data is empty

 1
Author: dekameron, 2013-07-14 15:12:12