Link to home
Start Free TrialLog in
Avatar of andy22
andy22

asked on

Loading JavaScript Arrays with MySQL Data using php

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>
Avatar of VGR
VGR

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]
?>
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
Avatar of andy22

ASKER

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
If I were you, I would reconsider my technique.
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
Avatar of andy22

ASKER

It is not OR, it is the carriage return in paragraph..
Avatar of andy22

ASKER

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..
ASKER CERTIFIED SOLUTION
Avatar of girish_nair
girish_nair

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of andy22

ASKER

Thanks Girish,
I got it.  It was /n/r... Thanks for your help..
I am transferring you these points..
Ankur Shah
it'll be inefficient
:(

But it works as we need :-)
Remember that if you are using addslashes() and ereg_replace() both.
Then first do the addslashes then ereg_replace, else there will be problem :)