Make Your PHP Variables Available to JavaScript

For my Visitor Info module I needed to pull some info out of the database and make that info available to JavaScript. Following is the code I used to do just that.

<?php
  $visitors
= array();
  while (
$data = db_fetch_object($result)) {
   
// build an array to hold visitor data, this will be converted
    // to a javascript array with drupal_to_js()
   
$visitors[$data->ip]["ip"] = $data->ip;
   
$visitors[$data->ip]["ccode"] = $data->ccode;
   
$visitors[$data->ip]["cname"] = $data->cname;
   
$visitors[$data->ip]["state"] = $data->state;     
   
$visitors[$data->ip]["city"] = $data->city;
   
$visitors[$data->ip]["zip"] = $data->zip;     
   
$visitors[$data->ip]["latitude"] = $data->latitude;
   
$visitors[$data->ip]["longitude"] = $data->longitude;
  }
 
// convert the PHP $visitors array to a javascript array
 
drupal_add_js("var visitors = " . drupal_to_js($visitors) . ";", 'inline');
?>

Directly after a database call, $result contains the result of the sql query. The while loop is looping through these results and populating an array called 'visitors'. This array holds all the data needed to plot visitors on the map. Next is the really interesting line.

drupal_add_js("var visitors = " . drupal_to_js($visitors) . ";", 'inline');

drupal_to_js() converts PHP variables, arrays, etc. into their JavaScript counterparts. So here, the PHP $vistors array is converted to an object called 'visitors' in JavaScript. And the drupal_add_js() function makes it all available to the page. Then the JavaScript functions are able to use that data. Really sweet.

Next you see that I can access the data from the JavaScript array called 'visitors'.

function init() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    map.setCenter(new GLatLng(Drupal.settings.centerLatitude,
                      Drupal.settings.centerLongitude),
                      Drupal.settings.startZoom);
    for(id in visitors) {
      descrip = visitors[id].city + ", " +
                visitors[id].state + "<br>" +
                visitors[id].cname;
      addMarker(visitors[id].latitude,
                visitors[id].longitude,
                descrip);
    }
  }
}

NOTE: I did format the above functions to better fit the screen space.

Below is a screenshot of the actual results of 'addMarker(visitors[id].latitude, visitors[id].longitude, descrip);'

Contact Me

Feel free to contact me.

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.