1

Disclaimer: I'm an iOS developer with little JQuery, PHP or MySQL experience.

Here's the deal: I have a MySQL database containing Film info (FilmTitle, FilmGenre, FilmDirector, etc).

My goal is to:

  1. Grab just the Film Titles from the database and store them in an Array.
    I'm using PHP for this and its working fine.
  2. Pass this PHP Array to a JavaScript Array.
    This also works.
  3. Finally, using the JavaScript Array, I want to populate a drop-Down menu with its contents using createElement().
    This does NOT work.

I'm getting all sorts of goofy stuff: Some document.write() commands are working and some aren't; The drop-down menu isn't getting populated; etc.

First question: Is this even a good strategy to begin with? I figured that as the number of films in the database changes, the only way to properly update the drop-down menu would be to do what I described.

Second Question: This should all be in a PHP file, not an HTML file, correct? But can PHP even execute JavaScript functions? Or does something special need to be done to make this work?

The code

<?php
echo "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
echo "<allFilms>";

$link = mysql_connect(" . . . .  ");
$query = "select * from FilmsSmallTable";
$result = mysql_query($query);
// Declare array variable:
$allFilmTitles = array();

    while($row = mysql_fetch_assoc($result))
    {
        echo "<film>";

            echo "<FilmName>";
            echo $row['FilmTitle'];
            array_push($allFilmTitles, $row["FilmTitle"]);
            echo "</FilmName>";

        echo "</film>";
    }

// Print array out to verify:    
echo "Here is the array's full contents:<br/>";
print_r ($allFilmTitles);

//convert array to string using ":#:" as separator
$stringedArray = implode(":#:",$allFilmTitles);

echo "<br/><br/>";
echo "PHP Array converted to a PHP String (the 'stringedArray' variable) = <br/>";
print_r ($stringedArray);
echo "</allFilms>";
?>

<html>
<head>
<title>PHP & JS</title>

<script type="text/javascript">

function showArray() {
   //Convert PHP string to JavaScript string
   var JSArrayString = "<? print $stringedArray; ?>";

  //Create JavaScript array
   var JSarray = new Array();

   var x;
   //Fill JavaScript array from the converted string   
   JSarray = JSArrayString.split(":#:");
   // And sort it:
   JSarray.sort();

   //document.write("JSarray's length = ", JSarray.length);
   document.write("JSarray contains: ", JSarray);

   // reset the Form's drop-down menu to contain no elements:
   FilmsDropDownMenu.length = 0;

   for (counter = 0;  counter < JSarray.length; counter++) {
    document.write("Counter = " + counter + "<br/>");
    var newMenuItem=document.createElement("option");
    newMenuItem.text = JSarray[counter];
    try {
        //currentMenu.add(newMenuItem, null); // standards compliant
        FilmsDropDownMenu.add(newMenuItem, null); // standards compliant
    }
    catch(ex) {
        //currentMenu.add(newMenuItem); // IE only
        FilmsDropDownMenu.add(newMenuItem);
    }
}


function displayUsersChoice() {
// Grab the INDEX number of the choice the user selected from that menu:
var tempMenu = document.getElementById("FilmsDropDownMenu").selectedIndex; 
choice = tempMenu[choiceSelected].value;
alert ("You chose: " + choice);
}

</script>


</head>

<body onload="showArray()">
Hello!

<form id="myForm">
<select id="FilmsDropDownMenu" onChange="displayUsersChoice()">
    <option>==Choose Film to Edit:==</option>
    <option>Star Wars</option>
    <option>Raiders</option>
    <option>2001</option>
</select>

<input type="submit" value="Display Array" onclick="showArray()" />
</form>

<br/>

</body>
</html>
7
  • 2
    I would use json_encode() to pass the array from PHP to JS in JSON format, then go from there. Commented Jun 1, 2012 at 13:36
  • 1
    Since you're creating the list from PHP and then just translating it via javascript to a HTML drop down, is there any reason not to just create the drop down directly with PHP? Commented Jun 1, 2012 at 13:38
  • I agree, I would do the same with json_encode, if you use jquery you will be able to handle the asynchronous calls better to ensure you create your menu correctly. Essentially you will be performing an ajax call in jquery and iterating through the json array to build up your menu. Commented Jun 1, 2012 at 13:39
  • Technically PHP isn't creating the drop down menu but you can use it to do so. I'll post an answer since there's no space here. Commented Jun 1, 2012 at 13:42
  • @h00ligan - thanks, will look forward to your code. Commented Jun 1, 2012 at 13:43

1 Answer 1

3

This is just an example how you can create the drop down directly from PHP. Sometimes the easy way is the right way:

$allFilmTitles = array("Godfather", "Colombo", "Naked Gun");
print '<select name="FilmsDropDownMenu" id="FilmsDropDownMenu">';

foreach ($allFilmTitles as $film)
{
    print "<option>{$film}</option>";
}

print "</select>";
Sign up to request clarification or add additional context in comments.

6 Comments

If you're looking to do a proper AJAX application then this is of course the completely wrong way of doing it. Then I'd recommend using json_encode etc. as others have suggested.
I would just change $filmArray to $allFilmTitles, as this is the name of the array in the OP. Then the <select> would be <select id="FilmsDropDownMenu">.
ok all - lemme try this and see how it goes...will report back soon :-)
@h00ligan- this worked very nicely - thank you - HOWEVER... My original question still looms: can I have JS stuff in my PHP file? For example, ordinarily, once the user makes a selection from the drop-down menu, the "onChange" event would trigger - and here I'd call a JS function I'd be writing - so how would that be done? (FYI, for what its worth, the ultimate goal is to create a CMS that lets the user edit their Database. They come to this page, select the movie entry they want to edit from drop-down menu, enter new data into text-fields, hit submit - and it updates the DB...)
You can have JS stuff in your PHP file but the javascript can't invoke the PHP code, this is because all the PHP code is executed on the server before the HTML/Javascript is passed on to the browser. The browser then only sees and runs the javascript but has no knowledge of the PHP code. This is what AJAX is used to solve, the browser reacts on an action (onChange for example) and there you must perform an XMLHTTPRequest to the server to either load or save data. You can also do it in a similiar way as your original attempt, by creating the javascript data with PHP and use javascript (contd)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.