Link to home
Start Free TrialLog in
Avatar of codeAK
codeAK

asked on

send multiple checkbox selections from child form back to single parent field and close child window in php/JavaScript

I have a parent page/form that the user is filling in and when the user checks yes to a certain question on that form, a new pop up window opens (I use javaScript onClick for that). On the child page, a list of checkboxes is given - the values for which are pulled from a MySQL database using php. I want to pass the values of the checked checkboxes back to the parent screen and then close the child/popup. In php on the child screen, I have no problem setting a session var with the checked values (an array) which can be accessed from the parent page on a reload. However, in php, I do not know how to close the child window. In JavaScript, I know how to close the child window but don't know how to send an array value back to the parent screen textbox area field. Can anyone help me with this puzzle?
Avatar of b0lsc0tt
b0lsc0tt
Flag of United States of America image

codeAK,

Server side script like PHP can't close a window.  You would need to use JavaScript or other client side script.  I would use an iFrame to allow you to update the page without completely reloading it.  You can use JavaScript to update the iFrame.  My experience with this and PHP is limited but I have been real impressed with what I have learned and done.  I will try to come up with some sample code you can use if you are interested.  Otherwise an expert in this topic may be able to help you quicker with the specifics.

b0lsc0tt
Avatar of markdoc
markdoc

i made something like this a long time ago:

maybe this might help?

listing 1. pizza.html
<html>
<script language="javascript">
<!--
function toppings(page, name)
{
      var win = window.open(page, name, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=299,resize=0');            
      if (win.opener == null) win.opener = self;
}
//-->
</script>
<body>      
      <p>
            Do you want add more toppings? <input type="button" value="Yes" onclick="toppings('toppings.html', 'popup');"><br>            
      </p>
      <form name="parentForm"><input name="toppings" value="" /></form>
</body>
</html>

listing 2: toppings.html
<html>
<script language="javascript">
<!--
function updateParent() {    
    s = "";
    for (i = 0; i < 6; i++)
    {
          chk = eval("self.document.childForm.t" + i);
          if (chk.checked)
                s += chk.value + ", ";
    }
    opener.document.parentForm.toppings.value = s;
    self.close();
    return false;
}
//-->
</script>
<body>
      <form name="childForm" onsubmit="updateParent();">
            <p>Choose topping(s):<br>
                  <input type="hidden" name="order_taken" value="1" />
                  <input type="checkbox" name="t0" value="Pepperoni" />&nbsp;Pepperoni<br>
                  <input type="checkbox" name="t1" value="Anchovies" />&nbsp;Anchovies<br>
                  <input type="checkbox" name="t2" value="Extra Cheese" />&nbsp;Extra Cheese<br>
                  <input type="checkbox" name="t3" value="Bacon" />&nbsp;Bacon<br>
                  <input type="checkbox" name="t4" value="Shrimp" />&nbsp;Shrimps<br>
                  <input type="checkbox" name="t5" value="Extra Onions" />&nbsp;Extra Onions<br>
                  <input type="submit" value="Submit" />
            </p>
      </form>
</body>
</html>
Avatar of codeAK

ASKER

Thank you Markdoc. I am trying something very similar to what you have here except that because I pull the checkboxes from a database each time, there can be a varying number of them and I dealt with this by using an array for the checkboxes (input type=checkbox name=mathstds[] value=whateverIGotFromDatabase). So, how do I get my checked array values from that field compiled into a string in javaScript (I can only do it in php as I don't know much JScript) to send back to parent screen?
Avatar of codeAK

ASKER

In the child my function to update the parent
function copyToParent()
{
     var s = document.childform.childfield.value;
     window.opener.document.parentform.parentfield.value = s;
    window.close();
    return false;
}

the checkboxes are contained in a div construct and I loop through a DB results set creating what I want to print in each row with the checkbox so the checkbox code consists of a bunch of lines like the following
<input type=checkbox name=choices[] value=" . $phpvarfromDB . '>' $rowprint . "</p>";




hi codeAK, i'm glad i'm on the right track, why not try something like this?

listing 1. pizza.php
<html>
<script language="javascript">
<!--
function toppings(page, name)
{
     var win = window.open(page, name, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=299,resize=0');          
     if (win.opener == null) win.opener = self;
}
//-->
</script>
<body>    
     <p>
          Do you want add more toppings? <input type="button" value="Yes" onclick="toppings('toppings.php', 'popup');"><br>          
     </p>
     <form name="parentForm"><input name="toppings" value="" /></form>
</body>
</html>

listing 2: toppings.php
<?php

// . . .

$res = mysql_query("SELECT `value`, `caption` FROM `some_database`") or die(mysql_error());

$i = 0;
$checkboxes = "";
while (($row = mysql_fetch_assoc($res)))
{
      $checkboxes .= "<input type=checkbox name='chk$i' value=$row[value] />&nbsp;$row[caption]<br>";
      $i++;
}

$page = <<< EOPAGE
<html>
<script language="javascript">
<!--
function updateParent() {    
    s = "";
    for (i = 0; i < $i; i++)
    {
          chk = eval("self.document.childForm.chk" + i);
          if (chk.checked)
                s += chk.value + ", ";
    }
    opener.document.parentForm.toppings.value = s;
    self.close();
    return false;
}
//-->
</script>
<body>
      <form name="childForm" onsubmit="updateParent();">
            <p>Choose topping(s):<br>
                  $checkboxes
                  <input type="submit" value="Submit" />
            </p>
      </form>
</body>
</html>
EOPAGE;

$echo $page;

?>
this way you dynamically create the checkboxes and the script that iterates over the them to check if they are indeed checked. :)
Avatar of codeAK

ASKER

I am creating the checkboxes (which I can do individually instead of as an array) in php code on the server. I do a lot of other proecessing before I create the checkbox and I know php much better than javaScript. How can I pass the counter to the javaScript if I do them individually instead of as an array but in php?

can i see a code sample? i might be able to help more if i had a clearer picture of how you do it.
Avatar of codeAK

ASKER

Is there no way to pass the value of an array (checkbox defaults to sending only checked boxes anyway) back to a field on the form/parent using JavaScript?
i'm sure there is a way of doing what you want but you're getting me lost on what 'exactly' you want codeAK. now, if you could provide some code similar to what youre doing, then perhaps i can come up with something.
Avatar of codeAK

ASKER

Code for Parent
First I have a code block of php that does a bunch of stuff (populates part of form from the database, checks user inputs, preps input for write to database and eventually writes finished form to database)
and then I have this javaScript prior to my HTML stuff.
<script language="JavaScript">
var mathGLEs

      function openPopUp(url)
      {
            mathGLEs = window.open(url, "MathStds", "resizable, scrollbars, top=0, width=550, toolbar=no, menubar=no, left=440");
            mathGLEs.focus();
            if (!mathGLEs.opener)
                  mathGLEs.opener = self;
            
      }
      
      
         
</script>

later on, here is my form line
<form method="POST" name="PELEM" action="<?php echo $_SERVER['PHP_SELF'] ?>">

further down, I open this pop up using
 <td class="style14">Will your student study this subject?
                            <label>
  <input type="radio" name="studyMath" value="Yes" onclick="return openPopUp('k8mathcheck.php')">
  Yes</label>                            <label>
  <input type="radio" name="studyMath" value="No">
  No</label>                            <label></label></td>


On the pop up
<?php

// when the screen loads populate it with math standards from the database and place focus
//$sqlgetstandards = "SELECT substemID, subject, grade_level, stem_description, substem_description FROM mathgles";
      $sqlgetstandards = "SELECT a.stemID, a.subject, a.grade_level, a.stem_description, b.substemID, b.substem_description from mathstems as a LEFT JOIN mathsubstems as b on a.stemID = b.stemID where a.subject='Math' ORDER BY a.grade_level";
      $dbConn = connectDB($_SESSION['host'], $_SESSION['user'], $_SESSION['pass'], $_SESSION['db']);
      if ($dbConn) {
            
            $result = @mysql_query($sqlgetstandards, $dbConn);
            if ($result) {
                  
                  //great, we have some math standards as expected
                  
                  while ($row = mysql_fetch_array($result)) {
                        
                        //split the string for display purposes
                    if ($stemID == $row['stemID']) {
                                    $rowstring .=  "and " . $row['substem_description'];
                    }
                    else {
                                      if ($grade != $row['grade_level']) {
                                          //we just switched to a new grade level so write an anchor into our block
                                          //<a name="K" id="K"></a>
                                          $optionblock .= "<a name=". "'" . $row['grade_level'] . "'" . " id=" . "'" . $row['grade_level'] . "'" . "></a>";
                                    }
                                      $grade = $row['grade_level'];
                                      $rowprint = $rowstring;
                                    $stemIDcheck = $stemID;
                                    $stemID = $row['stemID'];
                                    
                                    if ($row['grade_level'] == 0) {
                                          $rowstring = $row['stemID'] . " Grade K " . " " . $row['stem_description'];
                                          $rowstring .= $row['substem_description'];
                                    }
                                    else {
                                          $rowstring = $row['stemID'] . " Grade " . $row['grade_level'] . " " . $row['stem_description'];
                                          $rowstring .= $row['substem_description'];
                                    }
                                    
                              
                                    if ($rowprint != "") {
                                          $optionblock .= "<input type=checkbox name=mathstds[] value=".  $stemIDcheck . '>' . $rowprint . "</p>";
                                          $counter ++;
                                    }
                    }
                  }
            }
            else {
                  $error = "No math standards were found in the database. Please contact the IDEA help desk for assistance.";
            }
      }
      else {
            $error = "No database connection was made";
      }

if (isset ($_SESSION['Message'])) {
      echo $_SESSION['Message'];
      $_SESSION['Message'] = '';
}


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="JavaScript">
function copyToILP() {
      opener.document.PELEM.mathstds.value = document.mathGLEs.mathstds.value;
      window.close();
      return false;
}

</script>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>K-8 Math Standards</title>
<style type="text/css">
<!--
.style1 {color: #333333}
.style2 {color: #FF0000}
.style3 {
      color: #333333;
      font-size: 14px;
      font-weight: bold;
}
.style7 {
      font-size: 14px;
      font-weight: bold;
}
body {
      margin-left: 15px;
      margin-bottom: 50px;
}
-->
</style>
</head>

<body>
<form method="POST"  name="mathGLEs" onsubmit="copyToILP();"></form>
<p><img src="../images/staff_r1_c1.gif" width="500" height="50">
</p>

<p><span class="style2">
  <?php if (isset($error)) { echo "<p class=\"ErrorTxt\" align=\"center\">$error</p>"; } ?>
</span></p>
<p>Please click to check all the standards you want to include on your child's ILP. </p>
<p align="left" class="style1">When you are finished, click here
      
  <input type="submit" name="Submit" value="Submit"/>
</p>
<p align="left" class="style3">
</p>
<p align="left" class="style1"><strong> Go to standards for grade level: <a href="#0">K</a> * <a href="#1">1</a> * <a href="#2">2</a> * <a href="#3">3</a> * <a href="#4">4</a> * <a href="#5">5</a> * <a href="#6">6</a> * <a href="#7">7</a> * <a href="#8">8</a> </strong></p>


  <fieldset style="width: 500px; overflow: auto;">
  <legend class="style7">k-8 Math Standards</legend>
  <div style="width: 500px; height: 375px; overflow: auto;">
 
<?php echo $optionblock; ?>

  </fieldset>
     </span>  
    </span>  
</div>
<pre></p>
</pre>
<p>
 
</form>
</p>
</body>
</html>

Sorry if it's messy on the paste here. I have been fiddling around in the javaScript function copyToILP() according to your suggestions and have tried iterating there but I don't have access to my $counter php variable. I tried doing length of the array in javaScript there.

I have tried also with this in place
<script language="JavaScript">
function copyToILP() {
      var s = "";
      for (i=0; i < 100; i++) {
                  var chk = eval("self.document.mathGLEs.mathstds" + i);
                  if(chk.checked)
                  s += chk.value + ", ";
      }
      opener.document.PELEM.mathstds.value = document.mathGLEs.mathstds.value;
      self.close();
      return false;
}

</script>
still nothing.

Thank you
Avatar of codeAK

ASKER

now, I just tried using an onclick in my submit button rather than onsubmit with the form tag for the javaScript method and I have the method this way now for testing
function copyToILP() {
      
      opener.document.PELEM.mathstds.value = "test";
      self.close();
      return false;
}

this at least puts the word test into my correct field on the opener form and closes the child pop up.

now I just need to figure out how to send an array or make the array into a string using javascript?
ASKER CERTIFIED SOLUTION
Avatar of markdoc
markdoc

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 codeAK

ASKER

I tired this approach of iterating rather than using an array but what I discovered after some debugging is that the problem is not to do with the use of an array vs. iterating through individual fields and so this method does not work either for my situation. The reason your sample code works and mine does not is that your checkbox values are hardcoded into the HTML while mine are created using php variables constructed through some processing of dynamic data. Because the checkbox field values are php variables, the javaScript (client) cannot deal with the server side vars. This seems obvious now!  in the javaScript function, the value referred to by window.document.mathGLEs.mathstd is null. While I can keep an array list of the checkbox values as I'm creating them which I could then echo into the javaScript, I need to know which have been checked and pass in only an array or list of the checked boxes. So, I still need to think about the best way to do this. Your answers did help me to pin point the problem so thank you.

hi codeAK, i'm sorry but i don't think you get it yet. what you don't realize is that the only way to show a control in you browser is to write them as html code and send the whole script to the browser.  now there is only one way to do this "dynamically": you do whatever processing you want in your cgi script, in your case the php script, then let the script hardcode (as you erroneously put it) the checkboxes or whatever controls you want then output them to your browser. there is no other way to do this---that is as dynamic as it gets.

now, talking about an array of controls, you do have this array of controls in your 'document' object. but in order for this array of controls to exist, you must create the controls first in your html code just the same. of course you can create the controls "dynamically" (there's that word again) using javascript, but you will be facing a larger problem: javascripting is not server-side, thus you don't have access to your database. so now we go back to php, and if you want to read the first paragraph again, be my guest.
Avatar of codeAK

ASKER

No need to be sorry. I am glad you are still with me on this and trying to communicate and be helpful. I understand the difference between the php code running on the server and interfacing with the database and the client side HTML and javaScript code. I am sorry if I misused terminology.

I create the array of controls mathstds[] or a series of controls named mathstds$counter (I have tried this both ways according to your suggestion) in a section of php code inside a loop where each addition to the string looks like this
$optionblock .= "<input type=checkbox name=mathstds[] value=" . $stemIDcheck . '>' . $rowprint . "</p>";

Then in the actual form HTML, I do this inside of a fieldset and a div construct
<?php echo $optionblock; ?>

This all works fine to produce the checkboxes as I expect.

In the javaScript code in this same form, I was trying to access the values of these checkbox fields or the field array like this
for an array, I tried
window.document.nameOfPopUpForm.mathstds.value
and window.document.nameOfPopUpForm.mathstds(i).value
and for a series of checkboxes, I tried
window.document.nameOfPopUpForm.mathstds$counter.value  (passing the $counter variable with an echo and php tags)

I never seemed to be getting the value of the actual field mathstds from the form in the javaScript even though I could get the expected value from the field using some php so I knew it was "there".  What I was trying to convey in my last message to you was that I thought maybe this was because of the way I set the value in the first place. Based on your comments, I guess it must be instead that I have incorrect javaScript syntax or am doing this piece incorrectly. If you can see what is wrong, please let me know.

So, since I felt defeated in that approach, now I have put the task of sending the values of the checkboxes back to the parent form into the php code like this
$arrmathstds = isset($_POST['mathstds']) ? $_POST['mathstds'] : '';
if (isset($_POST['Submit'])) {
  $_SESSION['mathstds'] = $arrmathstds;
  session_write_close();
  $s = "<scripot language=\"JavaScript\">\n";
  $s .= "window.opener.location.reload();";
  $s .= "</script>";
  echo $s;
}

Then, in the form tag, I put action="<?php echo $_SERVER['PHP_SELF'] ?>"
and on the parent form, I do a check onload for that session var and if I find it, I unpack the array and format for the input box on that screen. I feel like there must be an easier way to do this, but at least this way, when the submit button on my popUp is pressed, the session var containing the checked boxes only is available to the parent form and the child window closes with the javaScript that I sent to the browser. On reload of the parent, the data is there in the field. When the processing is over on that parent form, I just clean up the session.

I appreciate your time and input and am happy to have a work around now. If you see what was wrong in the first javaScript attempts, please fill me in.
Thank you