Jump to content

I Would Like To Pull Data From Mysql And Pass It To Javascript


confused and dazed

Recommended Posts

Hello internet. I did some searching on the topic so I believe it is possible to do. I tried a couple things and I am not getting anywhere. Here is what I would like to do. I have a javascript function that pre-loads values to buttons on a page - it works well. Here is the code: var Tload = [{id: 'tp1', value: ' Chicago ' },{id: 'tp2', value: ' LA ' },{id: 'tp3', value: ' Miami ' }, ]; window.onload = function() { for (var i = 0; i < Tload.length; i++) { document.getElementById(Tload.id).value = Tload.value; } What I would like to do is pull data from my database to use instead of typing in Chicago/LA/Miami... I would like these values to come from mysql database. How do I make this happen?

Link to comment
Share on other sites

js cant interact directly to mysql database so you need a php page which will do that. and you need js (more specificaly ajax) to request that php page which will generate some json encoded strings. you will get that string as response and will pass it to js function for parsing the JSON string like james said. and after that you can work with that data to manupulate the page.

Link to comment
Share on other sites

O.K. so its my fault here. I dont think I am explaining what I am trying to do well enough. I will try again...I have used the Tload array to populate textbox values upon loading the webpage.I have a different page that the administrator of the site would go in and submit new values (to the database) that will replace the ones already stored in the Tload array.Once an ordinary user refreshes the page they are looking at - the values for the towns will load differently based on the data the administrator last updated from the administrator page. My html code is as below (this is what the ordinary user will see when they open the page). How do I update the towns that the administrator sent to the database where the administrator does this from a different form on a different page than what the user is working with?<HTML><HEAD><script type="text/javascript">var Tload = [{id: 'tp1', value: ' Chicago ' },{id: 'tp2', value: ' L.A. ' },{id: 'tp3', value: ' Miami ' },];window.onload = function() { for (var i = 0; i < Tload.length; i++) { document.getElementById(Tload.id).value = Tload.value; }}</script><style type='text/css'>td{font-family:Times New Roman; color:black; font-size: 10pt; font-weight:bold;}</style></HEAD><form name=Tourney method="post"><table width="20%" border=1 cellspacing=0 cellpadding=0 style="color:black; float: left; margin-left: 1px"> <tr> <td align=center> <input readonly=textbox name=town1 value="" id="tp1" style="font-size: 6.5pt; text-align:left"> <input type=text name="response1" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town2 value="" id="tp2" style="font-size: 6.5pt; text-align:left"> <input type=text name="response2" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town3 value="" id="tp3" style="font-size: 6.5pt; text-align:left"> <input type=text name="response3" Value""></td></tr><tr><td><input type="submit" name="submit response" value="submit response"></table></form></html>

Link to comment
Share on other sites

How do I update the towns that the administrator sent to the database where the administrator does this from a different form on a different page than what the user is working with?
Do you want the towns to update the textbox values without the user pressing F5? (I doubt this is the case) - but if so, you'll need AJAX to contact PHP every xx seconds. Otherwise, just use the method I described above.When the user presses F5, the new towns will be fetched from the database into PHP, PHP will send them to JS, then JS can fill the textboxes.You'll need a .php file for that, I'd recommend having a .js file, and the .html file isn't really needed as you can just put the HTML code inside the PHP file, using ?> and <?php to toggle between PHP code/HTML code.
Link to comment
Share on other sites

"fetch the values from the database and store them in an array, then use json_encode() on the array" – Have I done this part correctly?$result = mysql_query("SELECT * FROM pass1 WHERE grp='1'", $con);while ($row = mysql_fetch_array($result));json_encode($row); "and echo that string to the browser, then in JS you can use JSON.parse( string ) to create the Tload array"I'm not sure how to do this part… please help. I have been trying for a while now… no success.

Link to comment
Share on other sites

My exposure to AJAX has been limited to the very simple situation of adding something like a table to the bottom of a page. That is the only AJAX coding I have experience with so far. In a more general situation where a central portion or various portions of the page need to be updated is this accomplished using JSON? Or are there several options? Thanks.

Link to comment
Share on other sites

I'm not sure how JSON works. My response was to JamesB and hoping I could get a little help with my code.
Well, I'm fairly sure you are going to use AJAX for this. Have you used AJAX calls/handlers before?
Link to comment
Share on other sites

the first stage is to build a 2d array of the rows from the database:

$result = mysql_query("SELECT * FROM pass1 WHERE grp='1'", $con);$rows = array();while ($row = mysql_fetch_array($result)) {  $rows[] = $row;}

then to send that to the browser as JSON:

$json = json_encode($rows); echo '<script type="application/javascript">var Tload = '.$json.';</script>';

ajax doesn't need to be used for this to work. ajax is just used to send/receive bytes to/from a web server/browser, the data can be encoded as JSON, XML, or any format you want. edit: in fact I don't think you even need to use JSON.parse, my bad.

Link to comment
Share on other sites

I am getting this error when using the code below. Any help would be appreciatedWarning: Unexpected character in input: ''' (ASCII=39) state=1 in F:\Hosting\\html\p1.php on line 86 I saved this as a .php file... what is wrong below? <html><head><style type='text/css'>td{font-family:Times New Roman; color:black; font-size: 10pt; font-weight:bold;}</style><script type="text/javascript">var Tload = [{id: 'tp1', value: '' },{id: 'tp2', value: '' },{id: 'tp3', value: '' },];window.onload = function() { for (var i = 0; i < Tload.length; i++) { document.getElementById(Tload.id).value = Tload.value; }}</script></head><form name=tourney action="p1.php" method="post"><table width="20%" border=1 cellspacing=0 cellpadding=0 style="color:black; float: left; margin-left: 1px"><tr> <td align=center> <input readonly=textbox name=grpe value="Enter Group" style="font-size: 6.5pt; text-align:left"> <input type=text name="grp1" Value""></td></tr><tr> <td align=center> <input readonly=textbox name=town1 value="" id="tp1" style="font-size: 6.5pt; text-align:left"> <input type=text name="response1" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town2 value="" id="tp2" style="font-size: 6.5pt; text-align:left"> <input type=text name="response2" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town3 value="" id="tp3" style="font-size: 6.5pt; text-align:left"> <input type=text name="response3" Value""></td></tr><tr><td><input type="submit" name="submit response" value="submit response"></table></form></html> <?php$con = mysql_connect("XXX","XXX","XXX");if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("xxx", $con);$sql="INSERT INTO pass1 (grp,town1r,town2r,town3r)VALUES ('" . mysql_real_escape_string($_POST['grp1']) . "','" . mysql_real_escape_string($_POST['response1']) . "' ,'" . mysql_real_escape_string($_POST['response2']) . "' ,'" . mysql_real_escape_string($_POST['response3']) . "' )";if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }echo "Response collected";echo "<br>"; $result = mysql_query("SELECT * FROM pass1 WHERE grp='1'", $con);$rows = array();while ($row = mysql_fetch_array($result)) { $rows[] = $row;} $json = json_encode($rows); echo '<script type="application/javascript">var Tload = '.$json.';</script> mysql_close($con)?>

Link to comment
Share on other sites

on the 3rd to last line, you gotta close the PHP string with an apostrophe and semicolon:

</script>';

edit: also, you can change mysql_fetch_array to mysql_fetch_assoc, as the integer keys aren't needed. i'd also recommend putting <body> and </body> tags in your html code, and putting the closing body and closing html tags after all the PHP.

Link to comment
Share on other sites

Thank you. O.K. so it seems like I am almost there. The array is populated with the right data but the Tload loads the blanks and not the data in the array. Also - how do I keep the "response collected" from showing up on the page the first time it opens. <html><head><style type='text/css'>td{font-family:Times New Roman; color:black; font-size: 10pt; font-weight:bold;}</style><script type="text/javascript">var Tload = [{id: 'tp1', value: '' },{id: 'tp2', value: '' },{id: 'tp3', value: '' },];window.onload = function() {for (var i = 0; i < Tload.length; i++){document.getElementById(Tload.id).value = Tload.value;}}</script></head><body><form name=tourney action="p1.php" method="post"><table width="20%" border=1 cellspacing=0 cellpadding=0 style="color:black; float: left; margin-left: 1px"><tr> <td align=center> <input readonly=textbox name=grpe value="Enter Group" style="font-size: 6.5pt; text-align:left"> <input type=text name="grp1" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town1 value="" id="tp1" style="font-size: 6.5pt; text-align:left"> <input type=text name="response1" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town2 value="" id="tp2" style="font-size: 6.5pt; text-align:left"> <input type=text name="response2" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town3 value="" id="tp3" style="font-size: 6.5pt; text-align:left"> <input type=text name="response3" Value""></td></tr><tr><td><input type="submit" name="submit response" value="submit response"></table></form></body></html><?php$con = mysql_connect("xxx","xxx","xxx");if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("xxx", $con);$sql="INSERT INTO pass1 (grp,town1r,town2r,town3r)VALUES ('" . mysql_real_escape_string($_POST['grp1']) . "','" . mysql_real_escape_string($_POST['response1']) . "' ,'" . mysql_real_escape_string($_POST['response2']) . "' ,'" . mysql_real_escape_string($_POST['response3']) . "' )";if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }echo "Response collected";echo "<br>";$result = mysql_query("SELECT town1, town2, town3 FROM pass1 WHERE grp='1'", $con);$rows = array();while ($row = mysql_fetch_array($result)) {$rows[] = $row;}$json = json_encode($rows);echo '<script type="application/javascript">var Tload = '.$json.';</script>';mysql_close($con)?>

Link to comment
Share on other sites

first off you should put the closing body/html tags after the PHP, just to be sure. i was assuming you had a table with fields "id" and "value", but that's fine if you don't.regarding "id", (tp1, tp2, tp3 etc), is that stored in the table, or will it always be "tp" with an incrementing number on the end?and regarding "value" (Chicago, LA, Miami, etc), is that stored in field town1? or does it need to be town1 town2 and town3 all joined together? if tp has an incrementing number on the end, and "value" is stored in town1, you can change:

$rows = array();while ($row = mysql_fetch_array($result)) {	$rows[] = $row;}

to:

$rows = array();$i = 1;while ($row = mysql_fetch_array($result)) {	$rows[] = array(		'id' => 'tp'.($i++),		'value' => $row['town1']	);}

regarding the response collected, not really sure what you mean, but it sounds like sessions might be useful.

Link to comment
Share on other sites

If I dont change any of the code to what you suggested above and use only the code that I posted in response #17 above - upon loading the page the source code shows the following which I believe is correct town1 should be DET town2 should be CHI town3 should be LA (DET,CHI,LA come right from my database).How do I get these town to load into td1 td2 td3 when the page first loads up? <script type="application/javascript">var Tload = [{"0":"DET","town1":"DET","1":"CHI","town2":"CHI","2":"LA","town3":"LA"}];</script>

Link to comment
Share on other sites

$rows = array();$i = 1;while ($row = mysql_fetch_assoc($result)) {   $rows[] = array(	   'id' => 'tp'.($i++),	   'value' => $row['town1']   );   $rows[] = array(	   'id' => 'tp'.($i++),	   'value' => $row['town2']   );   $rows[] = array(	   'id' => 'tp'.($i++),	   'value' => $row['town3']   );}

Link to comment
Share on other sites

JamesB I do appreciate the time you are taking to walk me through this. Here is what the source code looks like when the page loads - and this looks right. However, DET CHI and LA are not loaded in the textboxes when the page loads. <script type="application/javascript">var Tload = [{"id":"tp1","value":"DET"},{"id":"tp2","value":"CHI"},{"id":"tp3","value":"LA"}];</script>

Link to comment
Share on other sites

yeah JSON is commonly used over AJAX, JSON can be used over anything though (eg. PHP's echo straight into JavaScript)
Is there a name for this technique? Thanks. I found these links; http://www.openjs.com/articles/ajax/transfer_methods_xmlhttprequest_alternatives.php http://caih.org/open-source-software/modularjs/loading-javascript-script-vs-ajax-vs-both/
Link to comment
Share on other sites

at the top of the window.onload function, try adding: alert(typeof Tload); // check if Tload var existsalert(Tload.length); // check length of array

Is there a name for this technique? Thanks.
well json_encode turns certain data types into a string, i think thats called serialization.
Link to comment
Share on other sites

Here is all the code so far... it is saying that Tload is undefined. <html><head><?php$con = mysql_connect("xxx","xxx","xxx");if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("xxx", $con);$result = mysql_query("SELECT town1, town2, town3 FROM pass1 WHERE grp='1'", $con);$rows = array();$i = 1;while ($row = mysql_fetch_assoc($result)) { $rows[] = array( 'id' => 'tp'.($i++), 'value' => $row['town1'] ); $rows[] = array( 'id' => 'tp'.($i++), 'value' => $row['town2'] ); $rows[] = array( 'id' => 'tp'.($i++), 'value' => $row['town3'] );}$json = json_encode($rows);echo '<script type="application/javascript">var Tload = '.$json.';</script>';?><style type='text/css'>td{font-family:Times New Roman; color:black; font-size: 10pt; font-weight:bold;}</style> </head><body><form name=tourney method="post"><script type="text/javascript">alert(typeof Tload); // check if Tload var existsalert(Tload.length); // check length of arraywindow.onload = function() {for (var i = 0; i < Tload.length; i++){document.getElementById(Tload.id).value = Tload.value;}}</script><table width="20%" border=1 cellspacing=0 cellpadding=0 style="color:black; float: left; margin-left: 1px"><tr> <td align=center> <input readonly=textbox name=grpe value="Enter Group" style="font-size: 6.5pt; text-align:left"> <input type=text name="grp1" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town1 value="" id="tp1" style="font-size: 6.5pt; text-align:left"> <input type=text name="response1" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town2 value="" id="tp2" style="font-size: 6.5pt; text-align:left"> <input type=text name="response2" Value""></td></tr> <tr> <td align=center> <input readonly=textbox name=town3 value="" id="tp3" style="font-size: 6.5pt; text-align:left"> <input type=text name="response3" Value""></td></tr><tr><td><input type="submit" name="submit response" value="submit response"></table></form> <?php$sql="INSERT INTO pass1 (grp,town1r,town2r,town3r)VALUES ('" . mysql_real_escape_string($_POST['grp1']) . "','" . mysql_real_escape_string($_POST['response1']) . "' ,'" . mysql_real_escape_string($_POST['response2']) . "' ,'" . mysql_real_escape_string($_POST['response3']) . "' )";if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); }echo "Response collected";echo "<br>";mysql_close($con)?> </body></html>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...