Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > PHP/MySQL > Pro PHP
Password Reminder
Register
Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
Pro PHP Advanced PHP coding discussions. Beginning-level questions will be redirected to the Beginning PHP forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Pro PHP section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developersí questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old December 6th, 2003, 02:25 PM
Registered User
 
Join Date: Jun 2003
Location: , , .
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Default Passing PHP variables to javascript

Hello Everyone,

  I have a problem with PHP as relates to javascript. I am trying to dynamically populate a listbox (dropdown box) from a MySQL database. The problem lies in attempting to pass the PHP array to a javascript function. The code is as follows: (please, no laughing)

<SCRIPT LANGUAGE="JavaScript" TYPE="Text/Javascript" RUNAT="SERVER">

</SCRIPT>

<?PHP

//firsttry2.php
//attempting dynamic listboxes

include "include/open_db.inc";
include "include/common_db.inc";

$sql = "SELECT DISTINCT printed FROM media";
$result = mysql_query($sql, $db);
$rows = mysql_num_rows($result);

?>

<HTML>
<HEAD>
<TITLE>Populate List Box</TITLE>

<SCRIPT>

function selectChange(control, controlToPopulate, ItemArray, GroupArray)
{
  var myEle ;
  var x ;
  // Empty the second drop down box of any choices
  for (var q=controlToPopulate.options.length;q>=0;q--) controlToPopulate.options[q]=null;
  if (control.name == "firstChoice") {
    // Empty the third drop down box of any choices
    for (var q=myChoices.thirdChoice.options.length;q>=0;q--) myChoices.thirdChoice.options[q] = null;
 }
  // ADD Default Choice - in case there are no values
  myEle = document.createElement("option") ;
  myEle.value = 0 ;
  myEle.text = "[SELECT]" ;
  controlToPopulate.add(myEle) ;
  // Now loop through the array of individual items
  // Any containing the same child id are added to
  // the second dropdown box
  for ( x = 0 ; x < ItemArray.length ; x++ )
    {
      if ( GroupArray[x] == control.value )
        {
          myEle = document.createElement("option") ;
          myEle.value = x ;
          myEle.text = ItemArray[x] ;
          controlToPopulate.add(myEle) ;
        }
    }
}
// End -->

</SCRIPT>

</HEAD>

<BODY>

<CENTER>
<BR/><BR/>

    <FORM NAME='myChoices' METHOD='post' ACTION=''>
    <TABLE WIDTH='600' BORDER='5' BORDERCOLOR='navy' BGCOLOR='#D7D7D7'>
    <SELECT ID='firstChoice' NAME='firstChoice' ONCHANGE="selectChange(this, myChoices.secondChoice, arrItems1, arrItemsGrp1);">
    <OPTION VALUE=0 SELECTED>[SELECT]</OPTION>
<?php
$sql1 = "SELECT DISTINCT size FROM media WHERE printed='$firstChoice'";
$result1 = mysql_query($sql1, $db);
$rows1 = mysql_num_rows($result1);
for($i=0;$i<$rows1;$i++)
{
    $arrItems1[] = mysql_fetch_array($result1);
    $arrItemsGrp1[] = $i;
}
    for($i=0;$i<$rows;$i++)
    {
        $data = mysql_fetch_object($result);
        echo "<OPTION>$data->printed</OPTION>";
    }
?>
    </select>

    <BR/><BR/>
    <SELECT ID='secondChoice' NAME='secondChoice' ONCHANGE="selectChange(this, myChoices.thirdChoice, arrItems2, arrItemsGrp2);">
<?PHP
$sql2 = "SELECT DISTINCT weight, finish FROM media WHERE printed='$firstChoice' AND size='$secondChoice'";
$result2 = mysql_query($sql2, $db);
$rows2 = mysql_num_rows($result2);
for($i=0;$i<$rows2;$i++)
{
    $arrItems2[] = mysql_fetch_array($result2);
    $arrItemsGrp2[] = $i;
}
?>
    </SELECT>
    <BR/><BR/>
    <SELECT ID='thirdChoice' NAME='thirdChoice'>

    </SELECT>

    </TABLE>
    </FORM>


</CENTER>

</BODY>
</HTML>

<?php

mysql_free_result($result);
mysql_close($db);

?>

Is what I am trying to do possible or am I just wasting time?
Any help would be much appreciated.
Thanks.
Reply With Quote
  #2 (permalink)  
Old December 6th, 2003, 09:21 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

This mark-up syntax is blasphemy: "<BR/>"

You're mixing xhtml with html and sort of defeating the purpose of the shortcut syntax. xhtml does not allow uppercase letters in tags.

Have a peak at my xhtml FAQ at:
http://p2p.wrox.com/topic.asp?TOPIC_ID=4028

Well one problem that you have is that PHP cannot run Javascript at the server level. I think that can be done with ASP, but not so for PHP. However, you can use PHP to create and generate JavaScript from the server level, all you'll need to remember is to escape special characters.

: )
Rich


:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
Reply With Quote
  #3 (permalink)  
Old December 6th, 2003, 10:45 PM
Friend of Wrox
Points: 2,570, Level: 21
Points: 2,570, Level: 21 Points: 2,570, Level: 21 Points: 2,570, Level: 21
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Here's a brief example of using PHP to generate javascript:


<?php

$colors = array("orange", "green", "blue", "red");


echo "<script language=\"JavaScript\">\n";
echo "<!-- hide from older browsers\n";

echo " var colors = new Array();\n";

foreach ($colors as $key => $color)
{
    echo " colors[\"$key\"] = \"$color\";\n";
}

echo "// -->\n";
echo "</script>\n";
?>

This will generate the following code:

<script language="JavaScript">
<!-- hide from older browsers
   var colors = new Array();
   colors["0"] = "orange";
   colors["1"] = "green";
   colors["2"] = "blue";
   colors["3"] = "red";
// -->
</script>


See, you can use PHP to generate javascript just as easily as you generate HTML.


Take care,

Nik
http://www.bigaction.org/
Reply With Quote
  #4 (permalink)  
Old December 9th, 2003, 03:03 PM
Registered User
 
Join Date: Jun 2003
Location: , , .
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi Nik,

Thanks for your suggestion. I tried what you showed me but I still keep getting the same error message.
Runtime Error! arrItems1 is undefined!

I even changed all my tags back to lowecase so as not to offend Rich again. Sorry Rich.

<?PHP

echo "<script Language=\"JavaScript\" Type=\"Text/Javascript\" Runat=\"Server\">";

echo "</script>";


//firsttry2.php
//attempting dynamic listboxes

include "include/open_db.inc";
include "include/common_db.inc";

$sql = "SELECT DISTINCT printed FROM media";
$result = mysql_query($sql, $db);
$rows = mysql_num_rows($result);

$sql1 = "SELECT DISTINCT size FROM media";
$result1 = mysql_query($sql1, $db);
$rows1 = mysql_num_rows($result1);
for($i=0;$i<$rows1;$i++)

{
    $arrItems1[] = mysql_fetch_array($result1);
    $arrItemsGrp1[] = $i;
}

$sql2 = "SELECT DISTINCT weight, finish FROM media WHERE printed='$firstChoice' AND size='$secondChoice'";
$result2 = mysql_query($sql2, $db);
$rows2 = mysql_num_rows($result2);
for($i=0;$i<$rows2;$i++)
{
    $arrItems2[] = mysql_fetch_array($result2);
    $arrItemsGrp2[] = $i;
}

echo "<html>";
echo "<head>";
echo "<title>Populate List Box</title>";

echo "<script>";

echo "function selectChange(control, controlToPopulate, ItemArray, GroupArray)";
echo "{";
  echo "var myEle;";
  echo "var x;";
  // Empty the second drop down box of any choices
  echo "for(var q=controlToPopulate.options.length;q>=0;q--) controlToPopulate.options[q]=null;";
  echo "if(control.name==\"firstChoice\") {";
    // Empty the third drop down box of any choices
    echo "for (var q=myChoices.thirdChoice.options.length;q>=0;q--) myChoices.thirdChoice.options[q] = null;";
 echo "}";
  // ADD Default Choice - in case there are no values
  echo "myEle = document.createElement(\"option\");";
  echo "myEle.value = 0;";
  echo "myEle.text = \"[SELECT]\";";
  echo "controlToPopulate.add(myEle);";
  // Now loop through the array of individual items
  // Any containing the same child id are added to
  // the second dropdown box
  echo "for (x=0;x<ItemArray.length;x++)";
    echo "{";
      echo "if(GroupArray[x]==control.value)";
        echo "{";
          echo "myEle=document.createElement(\"option\");";
          echo "myEle.value=x;";
          echo "myEle.text=ItemArray[x];";
          echo "controlToPopulate.add(myEle);";
        echo "}";
    echo "}";
echo "}";
// End -->

echo "</script>";

echo "</head>";

echo "<body>";

echo "<center>\n";
echo "<br/><br/>\n";

    echo "<form NAME='myChoices' METHOD='post' ACTION=''>\n";
    echo "<table WIDTH='600' BORDER='5' BORDERCOLOR='navy' BGCOLOR='#D7D7D7'>\n";
    echo "<select ID='firstChoice' NAME='firstChoice' ONCHANGE=\"selectChange(this, myChoices.secondChoice, arrItems1, arrItemsGrp1);\">\n";
    echo "<option VALUE=0 SELECTED>[SELECT]</option>\n";

    for($i=1;$i<$rows+1;$i++)
    {

        $data = mysql_fetch_object($result);
        echo "<OPTION value=$i>$data->printed</OPTION>\n";
    }

    echo "</select>";

    echo "<br/><br/>";
    echo "<select ID='secondChoice' NAME='secondChoice' ONCHANGE=\"selectChange(this, myChoices.thirdChoice, arrItems2, arrItemsGrp2);\">";

    echo "</select>";
    echo "<br/><br/>";
    echo "<select ID='thirdChoice' NAME='thirdChoice'>";

    echo "</select>";

    echo "</table>";
    echo "</form>";


echo "</center>";

echo "</body>";
echo "</html>";



mysql_free_result($result);
mysql_close($db);

?>
Reply With Quote
  #5 (permalink)  
Old December 9th, 2003, 03:36 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Quote:
quote:
I even changed all my tags back to lowecase so as not to offend Rich again. Sorry Rich.
lol, you aren't offending me! I was just trying to point out that what you were doing was counter-intuitive to the purpose of the technology.

You may use PHP to output JavaScript but it cannot be ran at the server level with PHP. Once you echo or print something from PHP it is output to the browser, lest you have output controls on but that's something totally unrelated to what you're trying to do. With PHP you have to think of JavaScript as purely client-side. It's downloaded to the browser and runs there and cannot run on the server. So the following will not work in any variation with PHP:

echo "<script Language=\"JavaScript\" Type=\"Text/Javascript\" Runat=\"Server\">";
echo "</script>";

Nik was saying think of and create your JavaScript as you would an HTML document, PHP can fill in the details on the server-side and output all that to the browser to be ran.

I looked at your original code a little while scratching my head trying to understand what you were trying to do. Can you explain what you expect in the output? Perhaps that will give us something to go on whereas one of us may provide you a working example of what you'd like to do.

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
Reply With Quote
  #6 (permalink)  
Old December 9th, 2003, 03:48 PM
Friend of Wrox
Points: 2,570, Level: 21
Points: 2,570, Level: 21 Points: 2,570, Level: 21 Points: 2,570, Level: 21
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Okay, you're not quite clear on something very important: There's a difference between server side (PHP) and client side (JavaScript) code execution. You can't just "share" variables between the two.

See, your PHP script runs and generates HTML and JavaScript code. PHP doesn't know or care what it's generating -- it's just output to PHP. It might as well be random characters for all PHP is concerned. The point is that PHP outputs text to the client.

Once the client gets this text, it's up to it to do something with it. 99.99% of the time, this text is HTML and/or JavaScript. The client's browser then runs any JavaScript code in the page. The client's browser doesn't have anything to do with the variables and functions defined within the scope of your PHP script.

In fact, the PHP script that generated the page is most likely not running anymore, which means that the PHP engine on your server doesn't even know about those variables anymore -- all the memory allocated to variables during your script's execution is reclaimed after the script terminates.


That all being said, you need to do what I mentioned in my first response: generate the proper JavaScript code that creates the variables you need to use from within JavaScript.

In my original example, I iterated over the $colors PHP array and generated the JavaScript code that would create a similar JavaScript array.

But it's very important to get this point: the $colors PHP variable is NOT "connected" or in anyway affiliated with the colors JavaScript variable.


The <script language="javascript" runAt="server"></script> tags are also completely useless -- there's nothing between the <script></script> tags, and JavaScript is NOT a server-side language.

Microsoft added some non-standard tweaks and extensions to ASP and IIS, so if you're using that setup, you can execute "javascript" code on the server, but it really makes little to no sense on any other platform (unless someone can prove me wrong).



Take care,

Nik
http://www.bigaction.org/
Reply With Quote
  #7 (permalink)  
Old December 9th, 2003, 03:52 PM
Registered User
 
Join Date: Jun 2003
Location: , , .
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi Rich,

I am glad you're not offended by my blasphemous coding technique.

All I want is the three select boxes to be populated from the fields in the database. The idea is to let people set their own items and customize the form to suit themselves. The array arrItems1[] should hold the list of items in that field but it keeps coming back as undefined. I am no expert at PHP so I don't understand why or what I need to do to initialize the array. When I test the code I just SELECT size FROM media to get everything in that field and then I echo it to the screen and it will display, but I am unable to pass it to the Javascript function. So what am I doing wrong?
Reply With Quote
  #8 (permalink)  
Old December 9th, 2003, 04:26 PM
Friend of Wrox
Points: 2,570, Level: 21
Points: 2,570, Level: 21 Points: 2,570, Level: 21 Points: 2,570, Level: 21
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I read through your code, and it looks like all you need to do is generate the javascript code to create and populate your arrays as javascript variables. This is pretty much the same thing I did with the $colors example above.

Here's how I would reorganize your script (functionally speaking):

<?php

// include files

// connect to database
// run your queries, create your result arrays

// BEGIN OUTPUT
// <html><head><title>..></title>

// BEGIN JAVASCRIPT
// <script language="JavaScript">
// generate your variable and function declarations and initializations.
// define selectChange() function here
// initialize your JS array variables here <--- use $colors example for reference
// </script>

// </head>
// <body>

// Generate your form HTML here.

// </body>
// </html>


Make sense?

Two more comments:

1) Whenever you output the value of an object's member variable from within a string, you should use curly-brace syntax to do so. You have the line:
    echo "<OPTION value=$i>$data->printed</OPTION>\n";

This should be
    echo "<option value={$i}>{$data->printed}</option>\n";

For more info: http://www.php.net/types.string


2) Your HTML/JavaScript output is inconsistent and messy. I like that you have great indentation style in your PHP code, but it's technically "not good style". Indentation should be used to differentiate levels of code block nesting. In HTML, tags within other tags increase the level of nesting. In PHP, curly-braces are the nesting delimiters.

You indented your PHP code where the HTML should be indented, but since most of the output you echo doesn't end in a newline character (\n), nor do you indent the actual strings you're outputting, the resultant HTML is really sloppy.

For example, this code:

echo "<html>";
  echo "<head>";
    echo "<title>my title</title>";
  echo "</head>";
echo "</html>";

Looks pretty, but it generates this:

<html><head><title>my title</title></head></html>


Does this help?


Take care,

Nik
http://www.bigaction.org/
Reply With Quote
  #9 (permalink)  
Old December 9th, 2003, 04:27 PM
Friend of Wrox
Points: 2,570, Level: 21
Points: 2,570, Level: 21 Points: 2,570, Level: 21 Points: 2,570, Level: 21
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I figured it'd be more useful if I cleaned up your code a little to show you what I mean. I haven't tested this at all -- it's all your original code with a couple comments added and some output formatting changes/fixes (added indentation and newlines to output).



<?php

// firsttry2.php
// attempting dynamic listboxes

include "include/open_db.inc";
include "include/common_db.inc";

$sql = "SELECT DISTINCT printed FROM media";
$result = mysql_query($sql, $db);
$rows = mysql_num_rows($result);

$sql1 = "SELECT DISTINCT size FROM media";
$result1 = mysql_query($sql1, $db);
$rows1 = mysql_num_rows($result1);
for($i=0;$i<$rows1;$i++)

{
    $arrItems1[] = mysql_fetch_array($result1);
    $arrItemsGrp1[] = $i;
}

$sql2 = "SELECT DISTINCT weight, finish FROM media WHERE printed='$firstChoice' AND size='$secondChoice'";
$result2 = mysql_query($sql2, $db);
$rows2 = mysql_num_rows($result2);
for($i=0;$i<$rows2;$i++)
{
    $arrItems2[] = mysql_fetch_array($result2);
    $arrItemsGrp2[] = $i;
}


// This is a simple utility function that appends a newline character to a
// string before outputting it.
function echol($str = "")
{
    echo "{$str}\n";
}

echol("<html>");
ehcol("<head>");
echol("<title>Populate List Box</title>");

echol("<script>");

echol("function selectChange(control, controlToPopulate, ItemArray, GroupArray)");
echol("{");
echol(" var myEle;");
echol(" var x;");

// Empty the second drop down box of any choices
echol(" for(var q=controlToPopulate.options.length;q>=0;q--) controlToPopulate.options[q]=null;");
echol(" if(control.name==\"firstChoice\") {");

// Empty the third drop down box of any choices
echol(" for (var q=myChoices.thirdChoice.options.length;q>=0;q--) myChoices.thirdChoice.options[q] = null;");
echol(" }");

// ADD Default Choice - in case there are no values
echol(" myEle = document.createElement(\"option\");");
echol(" myEle.value = 0;");
echol(" myEle.text = \"[SELECT]\";");
echol(" controlToPopulate.add(myEle);");

// Now loop through the array of individual items
// Any containing the same child id are added to
// the second dropdown box
echol(" for (x=0;x<ItemArray.length;x++)");
echol(" {");
echol(" if(GroupArray[x]==control.value)");
echol(" {");
echol(" myEle=document.createElement(\"option\");");
echol(" myEle.value=x;");
echol(" myEle.text=ItemArray[x];");
echol(" controlToPopulate.add(myEle);");
echol(" }");
echol(" }");
echol("}");


/////////////////////////////////////////////////////
// GENERATE YOUR JAVASCRIPT ARRAY VARIABLES HERE. //
/////////////////////////////////////////////////////

// End -->

echol("</script>");
echol("</head>");

echol("<body>");

echol("<center>");
echol("<br /><br />");

echol("<form NAME='myChoices' METHOD='post' ACTION=''>");
echol(" <table WIDTH='600' BORDER='5' BORDERCOLOR='navy' BGCOLOR='#D7D7D7'>");
echol(" <select ID='firstChoice' NAME='firstChoice' ONCHANGE=\"selectChange(this, myChoices.secondChoice, arrItems1, arrItemsGrp1);\">");
echol(" <option VALUE=0 SELECTED>[SELECT]</option>");

for($i=1;$i<$rows+1;$i++)
{
    $data = mysql_fetch_object($result);
    echol(" <option value={$i}>{$data->printed}</OPTION>");
}

echol(" </select>");

echol(" <br/><br/>");
echol(" <select ID='secondChoice' NAME='secondChoice' ONCHANGE=\"selectChange(this, myChoices.thirdChoice, arrItems2, arrItemsGrp2);\">");

echol(" </select>");
echol(" <br /><br />");
echol(" <select ID='thirdChoice' NAME='thirdChoice'>");

echol(" </select>");

echol(" </table>");
echol("</form>");


echol("</center>");

echol("</body>");
echol("</html>");


mysql_free_result($result);
mysql_close($db);

?>


Take care,

Nik
http://www.bigaction.org/
Reply With Quote
  #10 (permalink)  
Old April 4th, 2005, 10:24 AM
Registered User
 
Join Date: Apr 2005
Location: , , .
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Thanks for all your useful posts on the PHP to JS subject. :D

I have another small question on the subject.

Can PHP variables be passed to externally linked JS files? Obviously defining the PHP variables before calling the JS file.

I need to pass a PHP variable to a JS file as the file is used for configuring a DHTML menu that uses the config file in conjuction the main egine JS file to create the finished menu code.

Thanks

BuR

Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Passing Variables from Javascript/AJAX to VBScrip mperry Classic ASP Basics 3 November 12th, 2007 02:29 AM
Passing Javascript Variables to Asp.Net? Grumpy ASP.NET 2.0 Basics 4 September 8th, 2006 11:52 PM
Passing variables from HTML to php manunair PHP How-To 9 April 9th, 2006 11:27 PM
PHP passing variables to .swf file Ashleek007 Flash (all versions) 4 December 15th, 2004 08:38 PM
passing variables from PHP to Perl joconnor Beginning PHP 4 July 21st, 2004 08:13 AM



All times are GMT -4. The time now is 11:46 AM.


Powered by vBulletin®
Copyright ©2000 - 2018, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.