| | |
Inserting dynamic values into Javascript variables
Please support our JavaScript / DHTML / AJAX advertiser: 50% off 6 Months Dedicated Server Hosting from 1&1!
Thread Solved |
•
•
Join Date: Jun 2007
Posts: 1
Reputation:
Solved Threads: 0
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
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
Assume you have a db table called config with the columns: name, value.
php Syntax (Toggle Plain Text)
<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:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
<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:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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)
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.
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
xhr.onreadystatechange = function() { // js to handle the HTTP request };
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)
xhr.onreadystatechange = function() { // js to handle the HTTP request if (xhr.readyState == 4) { // HTTP Request complete } };
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)
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.
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
var configs = { 'name1' : 'value1', 'name2' : 'value2' };
In JSON:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
json_str = "{ 'name1' : 'value1', 'name2' : 'value2' }";
or
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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:
php Syntax (Toggle Plain Text)
// 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:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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.
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!
Cpanel Email - Let users Register email accounts on your website upon registration
Ajax Chat - Fully browser based chat!
![]() |
Similar Threads
- Capturing data from txt file using JavaScript/HTML (JavaScript / DHTML / AJAX)
- local variables (C++)
- dynamic combo load problems (PHP)
- variables from javascript in asp.net (ASP.NET)
- Passing variables to and from PHP (JavaScript / DHTML / AJAX)
- linkedlist (C++)
- external javascript (JavaScript / DHTML / AJAX)
Other Threads in the JavaScript / DHTML / AJAX Forum
- Previous Thread: help needed in coloring html tables
- Next Thread: New GreaseMonkey Script for DaniWeb
Views: 11413 | Replies: 1
| Thread Tools | Search this Thread |
Tag cloud for JavaScript / DHTML / AJAX
ajax ajaxcode ajaxhelp animate array automatically blackjack box bug calendar column content cookies css design detect developer div dom download dynamic element error explorer explosion file firefox flash focus font form function game getelementsbytagname google gwt hangman hide hijack html iframe image images index insertbefore internet internet-explorer java javascript javascripts jquery js list listbox maps marquee match mimic modal mp3 multiple mysql offline onclick onerror onmouseover parameters pass photo php player position post print programming regex resize script scroll scrollbar search select selection show size sorting synchronous text tooltip tweet variables vb.net video web webservice website window xml xspf \n






