April 28, 2012

Dynamically add options to a list through a hidden iframe

Question by user1157439

I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:

<?php echo 'var oInner  = document.createTextNode("'.$donnees["name"].'");'; ?>

because my code works perfectly with:

<?php echo 'var oInner  = document.createTextNode("Newoption");'; ?>

I don’t know why createtextnode doesn’t want to take my PHP var… I thought it could be a same origin policy since the database is located on a server outside my website.

I don’t know.

You’ll find enclosed the complete code:

In my HTML I have:

//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
    <option value"France">France</option>

//Empty region list
<select name="regionm" id="regionm">

//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>

In my Javascript I have:

//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
    var choixco = countrym.options[countrym.selectedIndex].value;
    document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;

In my PHP region.php file, I have:


// Get my choice
$codepays = $_GET['choix'];

//Retrieve the regions corresponding to the country
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();

// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);

//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");

//Here is my big issue:
<?php echo 'var oInner  = document.createTextNode("'.$donnees["name"].'");'; ?>

oOption.value = "none";
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");

$donnees = $req->fetch();

Answer by Starx

I am suspecting that the indexed element cannot be found. But is all cases, this below should work.

<?php echo 'var oInner  = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!