?
Solved

Loading JavaScript Arrays with MySQL Data using php

Posted on 2003-03-22
12
Medium Priority
?
655 Views
Last Modified: 2008-02-26
Hi there,
I want to load mysql data into javascript array to use it with javascript. I use the following script and I tried almost everything I can try.. Nothing works. Basically what I want to do from the following script is: I want to select some specifiv field say field no 2 from dropdown menu and display corresponding value in field 3 in the text area below the drop down menu from the same table.. Is there anything I can do using pure php because javascript is pain with php..
Here is my script
<?php

require("../logo.ade");
require("../conn.ade");
require("../functions_library.ade");
$result = mysql_query( "SELECT * FROM data_dictionary" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
?>

<html>

<head>

<title>DATA DICTIONARY</title>
</head>

<body>

<table border="0" cellspacing="0" cellpadding="0" align = "center">
<tr>
<td width="100%"><form name="ddmessage">
  <div align="center">
    <center>
    <table border="0" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="#111111" height="309">
<tr>
<td width="100%" align="center" height="65">
<p align="center"><select name="selectbox" size="1" onchange="changecontent(this)">
<option selected>Please Select from the following data element</option>
<?php
for ($count=0; $count < $num_rows; $count++)
{
$get_info = mysql_fetch_row($result);
?>
<option value=""> <?php echo($get_info[2]); ?></option>

<?php
echo ('<script language = "javascript">');
echo('var thecontents = new Array();');
echo ('function getdata()
{ ');
echo('thecontents[' . $count . '] = "' . $get_info['3'] . '";');
?>
}

<?php
}
?>
</script>
</select></p>
<p align="center"><br>
</td></tr><tr>
<td width="100%" align="center" height="244">
<textarea align = "center" rows="15" name="contentbox" cols="56" wrap="virtual"></textarea>
</td></tr></table></center>
  </div>
</form></td></tr></table>

getdata();
<script language="JavaScript">

function changecontent(which){
document.ddmessage.contentbox.value=thecontents[which.selectedIndex]}
document.ddmessage.contentbox.value=thecontents[document.ddmessage.selectbox.selectedIndex]
</script>
</body>
</html>
0
Comment
Question by:andy22
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 3
12 Comments
 
LVL 15

Expert Comment

by:VGR
ID: 8187279
I did it.
I even load a 2D array in javascript (it ain't easy, though :D )
It was, unsurprisingly, to populate dynamically a SELECT (listbox, drop-down menu, etc) with different data depending on a choice in an other SELECT (like "brand of car" -> "models available" or, below, "name or noeud" -> "list of names" or "list of noeuds")

Have a look at this code :

the important part is
<select name=Fapplique size=1 onchange=\"changement(this,saisie.Fapplique.options[selectedIndex].value);\">


<?
[snip, session_start(); includes etc]

echo <<<EOS
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from JavaScript-Impaired Browsers
 // spicifique noms et noeuds
 var globNb = new Array();
EOS;
echo "\nvar Noeuds = new Array(\"\"";
// this list has only one value
echo ",\"$sess_noeud\"";
echo ");\n";
echo "globNb[1]=1;\n";
echo "\nvar Noms = new Array(\"\"";
// this list has many values coming from the DB
$linkID=mysql_connect($dbHost,$dbLogin,$dbPassword) or die ("bad connect".mysql_error());
mysql_select_db($dbName,$linkID) or die ("bad select DB ".mysql_error());
$query="select distinct nom from $dbTableUsers order by nom asc;";
$result=mysql_query($query,$linkID) or die ("bad query get3 noeuds via $query. ".mysql_error());
$i=0;
while ($res=mysql_fetch_array($result)) {
  $i++;
  $locNom=$res["nom"];
  $locchoix[$i]=$locNom;
  echo ",\"$locNom\"";
} // while
echo ");\n";
echo "globNb[2]=$i;\n";
// final
// we build an array of the two prepared arrays
echo "\nvar globChoix = new Array(Noeuds,Noms";
echo ");\n";

// now handling functions
echo <<<EOS

function monindex(par)
{
var valeurloc = 0;
switch (par)
{

EOS;
for ($j=1;$j<=$i;$j++) echo "case \"".$locchoix[$j]."\":\nvaleurloc=$j;\nbreak\n";
echo <<<EOS
default:
 valeurloc=0;
}
return valeurloc;
}

function changement(obj,Value)
{
 // classique
 var dest   = obj.form.elements["Fparam"];
// in here, Fparam is the first SELECT's name, the one controlling the choices to offer in the second SELECT
//
 for (i=dest.options.length-1;i>=0;i--) dest.remove(i);
 zob=globNb[Value];
 for (i=1; i<=zob;i++) {
   zobu=globChoix[Value-1][i];
   nouvelleOption = new Option();
   nouvelleOption.text = zobu;
   nouvelleOption.value = zobu;
   dest.add(nouvelleOption, i);
 }
 return true;
}
// -->
</script>
EOS;

// here META-TAGS if you want
echo <<<EOS
<TITLE>my Title.com - $globFTitre</TITLE>
<LINK href="$courant/stylenew.css" rel=STYLESHEET type=text/css>
</HEAD>

[here normal BODY and HTML code]
// now the FORM where the jscript code is used
echo "<TABLE align=center border=1 cellPadding=0 cellSpacing=0 class=Tsondage>
                    <FORM action=$courant/nextpage.php/phase2 name=saisie method=post>
                    <TBODY>
                    <TR>
                      <TD class=gris vAlign=top width=200>&nbsp;Saisie de Nouvelle
                      </TD>
                    </TR>
                    <TR>
                      <TD><table>
                          <tr><td><FONT class=date>&nbsp;Titre (60c max)&nbsp;</td><td><INPUT class=inp name=Ftitre size=30 maxlength=60 value=$retT></font></td></tr>";
                          <tr><td><FONT class=date>&nbsp;S'applique `&nbsp;</td><td><select name=Fapplique size=1 onchange=\"changement(this,saisie.Fapplique.options[selectedIndex].value);\"><option value=1".(($retE==1)?' SELECTED':'').">noeud<option value=2".(($retE==2)?' SELECTED':'').">nom</select><BR>qui est :&nbsp;<select name=Fparam size=1>";
ListeNomNoeud($retE);
echo "</font></td></tr>
                          <tr><td><FONT class=date>&nbsp;Texte (2048c max)&nbsp;</td><td><TEXTAREA class=inp name=Ftexte ROWS=6 COLS=20 WRAP=\"soft\" MAXLENGTH=2048>$retD</TEXTAREA></font></td></tr>
                          </table>
                        <CENTER><BR><INPUT class=inp name=new type=submit value=Valider><BR><BR>
                        </CENTER></FONT>
                    </TD></TR>
            </TBODY>
            </FORM>
            </TABLE>";
[snip the rest]
?>
0
 
LVL 4

Expert Comment

by:girish_nair
ID: 8189223
Hi,

This will do the required thing :)


<?php

require("../logo.ade");
require("../conn.ade");
require("../functions_library.ade");
$result = mysql_query( "SELECT * FROM data_dictionary" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
//// note this change////
$opt='';
$js_arr='';
for ($count=0; $count < $num_rows; $count++)
{
$get_info = mysql_fetch_row($result);

$opt.="<option value=''> <?php echo($get_info[2]); ?></option>";

$js_arr.="thecontents[$count] = \"$get_info['3']\";\n";
}
//// note this change////
?>

<html>

<head>

<title>DATA DICTIONARY</title>
</head>

<body>

<table border="0" cellspacing="0" cellpadding="0" align = "center">
<tr>
<td width="100%"><form name="ddmessage">
 <div align="center">
   <center>
   <table border="0" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="#111111" height="309">
<tr>
<td width="100%" align="center" height="65">
<p align="center"><select name="selectbox" size="1" onchange="changecontent(this)">
<option selected>Please Select from the following data element</option>

<?php
echo $opt; //// note this change////
?>


</select></p>
<p align="center"><br>
</td></tr><tr>
<td width="100%" align="center" height="244">
<textarea align = "center" rows="15" name="contentbox" cols="56" wrap="virtual"></textarea>
</td></tr></table></center>
 </div>
</form></td></tr></table>

<script language="JavaScript">
var thecontents = new Array();
echo $js_arr; //// note this change////

function changecontent(which){

document.ddmessage.contentbox.value=thecontents[which.selectedIndex]

}
//document.ddmessage.contentbox.value=thecontents[document.ddmessage.selectbox.selectedIndex]
</script>
</body>
</html>


Cheers,
Girish
0
 

Author Comment

by:andy22
ID: 8190707
somehow, I made my code work but now the new problem is, it stores very good in an array but while dispaly, it gives me an error" unterminated string constant". My array contents even more than 1500 characters in each element and it is stored like a paragraph and may be terminated in the middle to start a new paragraph. I would like to diaplay my paragraph as it is. Is there any way, I can do that. and yes, some of the fields may have " inbetween. My array is so big that it is next to impossible to make changes in each and every element to make it only one line and to eliminate " from elements... (In short in text area I have a paragraph that I want to dispaly as it is)
Thanks
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 15

Expert Comment

by:VGR
ID: 8190726
If I were you, I would reconsider my technique.
0
 
LVL 4

Expert Comment

by:girish_nair
ID: 8192558
If you have " OR ' in the content, then use addslashes() when you assign the variables. And then put it in the JS.

$arr[0]=addslashes($variablename);

So your variable in JS will look like

str="abcd\"efgh\"......";
HTH
0
 

Author Comment

by:andy22
ID: 8197502
It is not OR, it is the carriage return in paragraph..
0
 

Author Comment

by:andy22
ID: 8197516
I mean OR is not a problem. Termination of paragraph to start a new paragraph is the problem.. Is there any way I can overcome that problem.. If I want to dispaly everything in just one line, my script can do that.. But I want to keep structure which is stored in an array as it is..
Please guide me..
0
 
LVL 4

Accepted Solution

by:
girish_nair earned 600 total points
ID: 8199977
You can do a
ereg_replace("\n\r","\\n",$str);

So that the content in javascript looks like

var str="hello \"andy22\",\nHow are you";

:)

Note: when you do this ereg replace the CRLF will be replaced by a \n. I hope you are getting it... Check if it is \r\n OR \n\r.
I use to forget many important things :)

Cheers,
Girish
0
 

Author Comment

by:andy22
ID: 8203843
Thanks Girish,
I got it.  It was /n/r... Thanks for your help..
I am transferring you these points..
Ankur Shah
0
 
LVL 15

Expert Comment

by:VGR
ID: 8203888
it'll be inefficient
0
 
LVL 4

Expert Comment

by:girish_nair
ID: 8207578
:(

But it works as we need :-)
0
 
LVL 4

Expert Comment

by:girish_nair
ID: 8207590
Remember that if you are using addslashes() and ereg_replace() both.
Then first do the addslashes then ereg_replace, else there will be problem :)
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question