Hi there,

I've been using PHP and MySql for some time now but I am quite new to Javascript.
I would like to know how it is possible to insert data stored in a MySql database into Javascript code.
For exmple, I am working on a travel guide site and would like to have a Google map for each location that is featured. I want to store the map grid reference for each location in the database and insert that value dynamically into the Google Maps code when a specific location is requested by the user.

Anyone have any ideas how this can be achieved?

Many thanks,

Simon

Hi there,

I've been using PHP and MySql for some time now but I am quite new to Javascript.
I would like to know how it is possible to insert data stored in a MySql database into Javascript code.
For exmple, I am working on a travel guide site and would like to have a Google map for each location that is featured. I want to store the map grid reference for each location in the database and insert that value dynamically into the Google Maps code when a specific location is requested by the user.

Anyone have any ideas how this can be achieved?

Many thanks,

Simon

Your can write some JavaScript variables into the JavaScript code embedded in the HTML Document:

Assume you have a db table called config with the columns: name, value.

<script>

var configs = {}; // config object

<?php

$array = $db->getResultArray('select name, value from configs'); // pseudo funciton that gets database results in an associative array
foreach($array as $name=>$value) {
echo "configs.$name = '$value'\r\n"; // configs.name = 'value';
}


?>

// the rest of your js

// example function
function getConfig(name) {
return configs[name];
}

</script>

The JS empbedded in your HTML document should look like:

<script>

var configs = {}; // config object

configs.name = 'value';
configs.name2 = 'value2';
// etc.. etc...

// the rest of your js

// example function
function getConfig(name) {
return configs[name];
}

</script>

The config object is just a generic JavaScript Object. The properties assigned to the object correspond to the results form the db.

So in your javascript code, if you wanted the row in the config table when the name was 'page_color'. This would be available in javascript on the client as:

config.page_color;

However, after the page is loaded, you cannot get new data from the database which is on the server, since the JS is now on the Client.
The only way to get data is to send an HTTP Request to the server, and in the response, have some data that can be read by JavaScript.

The new HTTP request can be achieved with an XMLHttpRequest or some other methods known commonly as AJAX.

If you use XMLHttpRequest, you make an HTTP Request via JavaScript, without reloading the page. The resulting HTTP Response is available to your JavaScript via a method of XMLHttpRequest that is fired when the HTTP Response progresses.
(you can seach docs on this on the web)

An HTTP Response from XMLHttpRequest is available either as plain-text or and DOM Document (XML).

You can either parse the plain-text version of the HTTP Response, or Traverse the DOM Object to get your data.

Say you make an XMLHttpRequest request.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
// js to handle the HTTP request
};
xhr.open('get', 'remoteData.php', true);

Now you requested the page: remoteData.php

This page will be returned to your JS as:

xhr.responseText; // the plain-text version

or

xhr.responseXML; // the DOM Document/Object

However, since an HTTP Request takes time to complete, the XMLHttpRequest can be set to run asynchronously, so that the JS execution does not stop. (otherwise the browser would hang until the HTTP Request was complete).

Therefore you have to specify a callback function, that will be called when the HTTP Request completes.

xhr.onreadystatechange = function() {
// js to handle the HTTP request
};

When the HTTP request is in progress, the method of the XMLHttpRequest Object, [I]onreadystatechange[/I] will be fired at different states in the progress.
The state is saved to the property, [I]readyState[/I].

xhr.onreadystatechange = function() {
// js to handle the HTTP request
if (xhr.readyState == 4) {
// HTTP Request complete
}
};

when the propertyreadyState == 4, the HTTP Request is complete.

So that means the HTTP Response will be available in responseText and responseXML.

Lets say in your php code on the page remoteData.php you have:

<?php

$array = $db->getResultArray('select name, value from configs'); 
foreach($array as $name=>$value) {
echo "configs.$name = '$value'\r\n"; // configs.name = 'value';
}

?>

Then you will have the string:

configs.name1 = 'value1';
configs.name2 = 'value2';

in xhr.responseText.

So you could have JavaScript eval() that string so that configs.name1 and configs.name2 is set to the corresponding values.

xhr.onreadystatechange = function() {
// js to handle the HTTP request
if (xhr.readyState == 4) {
// HTTP Request complete
eval(xhr.responseText);
alert(configs.name1); // value1
}
};

So you've essentially retrieved data from the remote database on the server, and put it into your JS code running client side.

The "standard" way of doing this would be to have the page remoteData.php return a JSON (JavaScript Object Notation) string. JSON is a subset of Javascript, which are the explicit notation of JavaScript Objects in a string. http://json.org/

An example of your configs Object in Object Notation would be:

var configs = {
'name1' : 'value1',
'name2' : 'value2'
};

In JSON:

json_str = "{
'name1' : 'value1',
'name2' : 'value2'
}";

or

json_str = '{
\'name1\' : \'value1\',
\'name2\' : \'value2\'
}';

Now to convert the JSON string to an Object, we would either parse the JSON string with a JSON parser, or just eval the string:

var json_str = '{
\'name1\' : \'value1\',
\'name2\' : \'value2\'
}';
var configs = eval(json_str);

Other programming languages are able to create JSON strings that when evaluated/parsed by JavaScript or JSON parser turn into JavaScript Objects. So PHP can send JSON strings to the JavaScript client, and the JS client can send JSON strings to PHP.

A good JSON class for PHP is the PEAR class "Services_JSON".
http://pear.php.net/pepr/pepr-proposal-show.php?id=198

If you use JSON, on your server side you'd have:

// get associative array from db
$array = $db->getResultArray('select name, value from configs'); 

// include the PEAR JSON class
require_once('json.php');
$JSON = new Services_JSON();

// encode the array as a JSON string
$json_str = $JSON->encode($array);
// echo the JSON string
echo $json_str;

On your client side would be just about the same:

xhr.onreadystatechange = function() {
// js to handle the HTTP request
if (xhr.readyState == 4) {
// HTTP Request complete
eval("("+xhr.responseText+")");
alert(configs.name1); // value1
}
};

Now since you have a PHP page on the server side, you can send HTTP params to it just like you would narmally, and keep track of sessions etc.

Example GET Request:

remoteData.php?clientid=1&task=getUpdates

Or send it a HTTP POST with JSON data and have the JSON class on the PHP side convert the JSON string into PHP Objects.

Google Maps should have resources on the subject, and also helpful examples if you go through the API or their googlemaps group.

commented: Nice +23
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.