Inserting dynamic values into Javascript variables

Please support our JavaScript / DHTML / AJAX advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
Thread Solved

Join Date: Jun 2007
Posts: 1
Reputation: loquela is an unknown quantity at this point 
Solved Threads: 0
loquela loquela is offline Offline
Newbie Poster

Inserting dynamic values into Javascript variables

 
0
  #1
Jun 27th, 2007
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
Reply With Quote Quick reply to this message  
Join Date: Sep 2005
Posts: 1,075
Reputation: digital-ether is just really nice digital-ether is just really nice digital-ether is just really nice digital-ether is just really nice 
Solved Threads: 66
Moderator
digital-ether's Avatar
digital-ether digital-ether is offline Offline
Veteran Poster

Re: Inserting dynamic values into Javascript variables

 
1
  #2
Jul 1st, 2007
Originally Posted by loquela View Post
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.

  1. <script>
  2.  
  3. var configs = {}; // config object
  4.  
  5. <?php
  6.  
  7. $array = $db->getResultArray('select name, value from configs'); // pseudo funciton that gets database results in an associative array
  8. foreach($array as $name=>$value) {
  9. echo "configs.$name = '$value'\r\n"; // configs.name = 'value';
  10. }
  11.  
  12.  
  13. ?>
  14.  
  15. // the rest of your js
  16.  
  17. // example function
  18. function getConfig(name) {
  19. return configs[name];
  20. }
  21.  
  22. </script>

The JS empbedded in your HTML document should look like:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <script>
  2.  
  3. var configs = {}; // config object
  4.  
  5. configs.name = 'value';
  6. configs.name2 = 'value2';
  7. // etc.. etc...
  8.  
  9. // the rest of your js
  10.  
  11. // example function
  12. function getConfig(name) {
  13. return configs[name];
  14. }
  15.  
  16. </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:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. 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.

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. var xhr = new XMLHttpRequest();
  2. xhr.onreadystatechange = function() {
  3. // js to handle the HTTP request
  4. };
  5. 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.

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. xhr.onreadystatechange = function() {
  2. // js to handle the HTTP request
  3. };

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

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. xhr.onreadystatechange = function() {
  2. // js to handle the HTTP request
  3. if (xhr.readyState == 4) {
  4. // HTTP Request complete
  5. }
  6. };

when the property readyState == 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:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. configs.name1 = 'value1';
  2. 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.

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. xhr.onreadystatechange = function() {
  2. // js to handle the HTTP request
  3. if (xhr.readyState == 4) {
  4. // HTTP Request complete
  5. eval(xhr.responseText);
  6. alert(configs.name1); // value1
  7. }
  8. };

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:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. var configs = {
  2. 'name1' : 'value1',
  3. 'name2' : 'value2'
  4. };

In JSON:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. json_str = "{
  2. 'name1' : 'value1',
  3. 'name2' : 'value2'
  4. }";

or

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. json_str = '{
  2. \'name1\' : \'value1\',
  3. \'name2\' : \'value2\'
  4. }';

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:

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. var json_str = '{
  2. \'name1\' : \'value1\',
  3. \'name2\' : \'value2\'
  4. }';
  5. 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:

  1. // get associative array from db
  2. $array = $db->getResultArray('select name, value from configs');
  3.  
  4. // include the PEAR JSON class
  5. require_once('json.php');
  6. $JSON = new Services_JSON();
  7.  
  8. // encode the array as a JSON string
  9. $json_str = $JSON->encode($array);
  10. // echo the JSON string
  11. echo $json_str;

On your client side would be just about the same:

  
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. xhr.onreadystatechange = function() {
  2. // js to handle the HTTP request
  3. if (xhr.readyState == 4) {
  4. // HTTP Request complete
  5. eval("("+xhr.responseText+")");
  6. alert(configs.name1); // value1
  7. }
  8. };

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.
www.fijiwebdesign.com - web design and development and fun
Cpanel Email - Let users Register email accounts on your website upon registration
Ajax Chat - Fully browser based chat!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the JavaScript / DHTML / AJAX Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC