Home php How to pass an array from php to javascript?

How to pass an array from php to javascript?

Author

Date

Category

There are two questions: 1) how to get from the database what I need. 2) how to transfer what I got from the base to javascript
i have html file.
it includes javascript map.js and a map.php file. java script is executed normally, but pkhp file is not executed like. how to bind javascript and pkhp together in html file, I don’t know. I have not studied pkhp and javascript, I have a slightly different specialization, but now I have to write something if necessary.

here is the map.php code:

& lt;? php
    $ hostname = "***************";
    $ username = "****************"; // username (Denwer's default is "root")
    $ password = "**********";
    $ dbName = "***********";
    $ table = "test_table";
    mysql_connect ($ hostname, $ username, $ password) or die ("I can't create a connection");
    mysql_select_db ($ dbName) or die (mysql_error ());
    $ query = "SELECT coord1, coord2 FROM $ table";
    $ res = mysql_query ($ query) or die (mysql_error ());
    mysql_close ();
? & gt;

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

then this array needs to be passed to javascript, here it is already initialized for me, but I need to fill it in from the database. The array is called markers.
map.js

var map;
var point = 1;
// points for the engine
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 () {
    //map
  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);
  // mark all points on the map
  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]));
  // map engine by points
  function mover () {
    map.panTo (new google.maps.LatLng (markers ["point" + point] [0], markers ["point" + point] [1]));
    point ++;
    if (point & gt; 10) point = 1;
  }
  // card is not used
  google.maps.event.addListener (map, 'idle', function () {
    setTimeout (mover, 500); // time in milliseconds
  });
  });

P.S.
since due to the lack of points there is no way to either give a plus or answer, I will write here.
Thank you Inkognitoo , dekameron for their help. I got what I wanted to implement. Everything works. I used the idea of ​​decameron. First or second time I work with pkhp. For a long time I was trying to buy what is the essence and why it does not work, it turns out I had an html file and in it & lt ;? ? & gt; and also & lt; script & gt; then I made index.php and drove html into echo, also drove javascript into echo. and inserted var markers in the right place. in general, thank you all for your help and your time.

BUT THE SOLUTION Deonisa turned out to be better because you don’t have to stuff everything into echo, you can use an html page and everything will be neat and clean. really it will not be shit code.

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


Answer 1, authority 100%

mysql_query (); returns not a table, but a handle of the resulting table. In your case, there are two columns with elements.
You can obtain values ​​from the descriptor, for example, the mysql_fetch_assoc ();
. An array of PHP in JavaScript is transmitted through the old good Echo . Read about it can here

Code may look something like this: (Visited 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 '};';

Answer 2, Authority 100%

My answer is more addition / comment on the answer @Dekameron .

Everything would be nothing but in the first answer, nor in yours, nothing is said about ajax . Type, left the vehicle food for reflection? ))

php

$ data = false;
if (mysql_num_rows ($ res) & gt; 0) {
  // If at least there is something, we form the answer
  While ($ myrow = mysql_fetch_assoc ($ Res)) {
    $ Data ['Point'. (++ $ i)] = Array ($ MyRow ['Coord1'], $ MyRow ['Coord2']);
  }
}
Echo JSON_ENCODE ($ DATA); // and do not add anything

JS

// send a request to map.php
$.ajax ({
  URL: 'MAP.PHP',
  Type: 'Post',
  datatype: 'json',
  Data: {Key: Val}, // if necessary
  SUCCESS: FUNCTION (DATA) {
    if (DATA) {
      Console.log (DATA); // All the coordinates obtained are exactly as required by the TC
    } else {
      // Actions in case the coordinates in the database are missing
    }
  }
});

Answer 3, Authority 50%

$ 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- & GT; $ Key = Array ($ MyRow ['Coord1'], $ myrow ['coord2']);
}
// in the right place:
echo 'var markers =' .json_encode ($ DATA). ';';

UPD

p.s. When will you stop it mysql_ * functions?

p.p.s. STDCLASS in order to bring curly brackets with a blank $ DATA, and not square

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions