Passing a value from a textbox to a child pop-up window

Hi folks,

  I have a page written in php ,

Open in new window

html and some javascript. It works well. I have a preview button in which I want to take the value from a textbox and display it in a child window. My script for popping up the child window works well, I just can't seem to get the value of the textbox passed to the child window.  I have posted the javascript, the html for the textbox and coding from my child window. The value that I am passing is html code. Any help appreciated....

This the textbox control - is placed between form tags.

 <table  align="center">
            <tr><td><textarea id="myhtml" name="supoffers" cols="80" rows="20"></textarea></td></tr>
        </table>

Open in new window

.

This is the javascript that calls the function to open a pop-up child window
<script type="text/javascript" language="javascript">
    var passVariable;
    function mkPreview() 
    
        {
	    var passVariable= document.getElementById("myhtml").value;
	    window.open('preview.html', 'Preview', 'width=600, height=600,left=70, top=70 scrollbars=yes resizable=yes menubar=no');
     }

</script>

Open in new window


This is the code in the child window - its the only code there
<script>
    document.write('opener.passVariable');

</script>

Open in new window

OverthereAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Any chance we can get a single script with a complete example that we can copy and install on our servers?
http://sscce.org/
Dave BaldwinFixer of ProblemsCommented:
You may need to use 'innerHTML' instead of 'value'.
var passVariable= document.getElementById("myhtml").innerHTML;

Open in new window

OverthereAuthor Commented:
Here you go. The textbox id "myhtml" contains html coding that I wish t render in the child pop-up page so they can see the results of what they entered..
saveoff.php is the parent page - coding listed below.
 preview.html is the child page (listed below saveoffer.php coding)

saveoffer.php

 <?php 
    require_once ("Includes/dbconfig.php");
    include("Includes/session.php");

   // Create database connection
    
      $databaseConnection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
   
      if ($databaseConnection->connect_error)
   
        {
     
               die("Database selection failed: " . $databaseConnection->connect_error);
  
        }
   
    $baderr= "";
// check button action section

// user has click preview button
 if (isset($_POST['preview']))
   { 
     //  header ("Location:saveoffer.php");
   }

// user has click clear button
 if (isset($_POST['clear']))
   { 
       header ("Location:saveoffer.php");
   }

// user has click on cancel button
    if (isset($_POST['cancel']))
   { 
       header ("Location:menu.php");
   }
// user has click on main menu button
if (isset($_POST['main']))
  
    {
     header ("Location:menu.php");
    }

// user has click on the save button
if (isset($_POST['submit']))
  
    {
      
        // intialize error message
        $baderr= "";

  // section to pull values from form  
     // country
       $country = $_POST["country"];
       //get stdmarketing value from the lookuptable
       $query = "select StdMarketLabel FROM countries where Country='$country'";
                 $result = $databaseConnection->query($query);
                 while($row = $result->fetch_assoc())
                      {
                         $countrylbl =  $row["StdMarketLabel"];
                      }
       //travel 
       $travel = $_POST["travel"];
       $query = "select StdMarketLabel FROM traveltypes where travel='$travel'";
                 $result = $databaseConnection->query($query);
                 while($row = $result->fetch_assoc())
                      {
                         $travellbl =  $row["StdMarketLabel"];
                      }
  
  
      // pulling html code pasted into textarea
      $rawoffer = $_POST['supoffers'];
      $goodoffer = htmlentities($rawoffer,ENT_QUOTES);

      $supplerid = $_SESSION["SupplierId"];
      $sqlsupplierid = $_SESSION["MsId"];
      $suppliername =  $_SESSION["SupplierName"];
    

      //check to make sure they have chosen atleast one tag
      // start of new coding section
      if (($country == 'None Selected' and $travel == 'None Selected') or ($goodoffer == ''))
         {  
               $baderr = "ERRORS:<BR>YOU MUST SELECT AT ATLEAST ONE TAG FOR SEARCHING.<BR>YOU MUST ENTER HTML CODING.";

         }else{
 // end of new coding section 
            $baderr = "";
            $databaseConnection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            if ($databaseConnection->connect_error)
               {
                    die("Database selection failed: " . $databaseConnection->connect_error);
               }else{

               // if they have chosen an option then insert record
                                 
             $sql = "insert into supplierlibrary(RecId,Name,SupplierPk,CountryStdMarket,
                     Country,TravelStdMarket,Travel,CampMsgBody)
                     values($supplerid,'$suppliername', $sqlsupplierid,'$countrylbl','$country','$travellbl','$travel','$goodoffer')";
                                        
               $res= $databaseConnection->query($sql);

               if (!$res)
                  {
                      $baderr = "ERROR<BR>FAILED TO INSERT RECORD<br>ERROR CODE:".$sql ."<BR><BR>" .$databaseConnection->error;
                      echo "<h7 style='color:#e80c4d;'>$baderr</h7>";
                     // echo "ERROR FAILED TO INSERT RECORD";
                     // echo "<BR><BR>";
                     // echo "ERROR<BR>" .$sql ."<BR><BR>" .$databaseConnection->error;
                      // allowed back into coding
                  }else{
                      $baderr = "RECORD WAS SAVED SUCCESSFULLY";
                      echo "<h7 style='color:'red';alignment-adjust: 'middle'>$baderr</h7>";
                      // moved here on 07-03
                      header ("Location:saveoffer.php");
                   }
              
                mysqli_close($databaseConnection);
                $baderr = "";
            }
           } 
              
    } else {
           // $baderr = "Username/password combination is incorrect. Please try again";
          
    }
?>


<script type="text/javascript" language="javascript">
    var passVariable;
    function mkPreview() {
        var passVariable = document.getElementById("myhtml").value;
       // document.write(passVariable); ///this writes on parent page - saveoffer.php...but need it to do it on child page - preview page
        window.open('preview.html', 'Preview', 'width=600, height=600,left=70, top=70 scrollbars=yes resizable=yes menubar=no');
    }

</script>
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
    
   <head>
     <title>Supplier Save Offer to Library</title>
     <link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" /> 
    </head>
     
    <body class="bodybg">
<form action="saveoffer.php" method="post">
    <br><br>
        <table align="center">
           <tr><td>Select any of the following tags to be for searching later.<br>You MUST choose atleast one.</br:>:</td></tr>
            <tr><td colspan="2">  <?php 
                       if (isset($_POST['submit']))
                       {
                          echo "<h7 style='color:#e80c4d;'>$baderr</h7>";
                       } ?>
             </td></tr>
            <tr><td align="right">Country:</td>
                <td align="left">
                <select name="country">
                <option value="None Selected" selected>Choose One</option>
        
                      <?php
                         $query = "select * FROM countries order by Country";
                         $result = $databaseConnection->query($query);
                         while($row = $result->fetch_assoc())
                              {
                                    ?><option value="<?php echo $row["Country"];?>"><?php echo $row["Country"];?></option>
                              <?php  }  ?>
                 </select>
                 </td>                                
                 <td align="right">Travel Type:</td>
                 <td align="left">
                 <select name="travel">
                <option value="None Selected" selected>Choose One</option>
        
                      <?php
                         $query = "SELECT * FROM traveltypes order by Travel";
                         $result = $databaseConnection->query($query);
                         while($row = $result->fetch_assoc())
                              {
                              ?>
                              <option value="<?php echo $row["Travel"];?>"><?php echo $row["Travel"];?></option>

                             <?php  }  ?>
                               </select>
             </td></tr>
            
        </table>
        <br><br>
             <table align="center">
            <tr><td>Paste HTML Code in textbox below</td></tr></table>

            <table align="center">
            <tr><td align="center">
                <input type="submit" name="submit" value="Save" src="images/Save.jpg"/></td>
                <td align="center"><input type="submit" name="cancel" value="Cancel" src="images/Cancel.jpg"/></td>
                <td align="center"><input type="submit" name="clear" value="Clear Form" src="images/Clear.jpg"/></td>
                <td align="center"><input  type="button" value="Preview Offer" onclick="javascript:mkPreview();" src="images/PreviewOffer.jpg"/></td>
                <td align="center"> <input type="submit" name="main" value="Main Menu" src="images/MainMenu.jpg"/></td>
                </td>
            </tr></table>
    <br>
       <table  align="center">
            <tr><td><textarea id="myhtml" name="supoffers" cols="80" rows="20"></textarea></td></tr>
        </table>

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

Open in new window


Preview.html


<script>
    document.write(opener.passVariable);


</script>

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

hieloCommented:
You could try appending the desired value to the html page.  So update the code as follows:
window.open('preview.html?data='+encodeURIComponent(passVariable), 'Preview', 'width=600, height=600,left=70, top=70 scrollbars=yes resizable=yes menubar=no');

Then on preview.html, try:

<script type="text/javascript">
    function gup( name,context )
{
 if(!context)
  context=window.location.href;
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "(^|[\\?]|&(amp;)?)"+name+"=([^&#]*)";
  var regex = new RegExp( regexS,"" );
  var results = regex.exec( context );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[3]);
}

var data = gup('data', location.href);
alert( data );
</script>

Open in new window

OverthereAuthor Commented:
I see what you are saying about innerHTML but I displayed the passVariable on the parent page - saveoffers - and it had what I had pasted into the textbox so it is getting the value. But if it is in keeping with good coding practice, I will change it.
hieloCommented:
>>I see what you are saying about innerHTML
 You are working with a textarea, so what you had initially is fine (meaning using the "value" instead of "innerHTML".  You would need the "innerHTML" if the element in question was not a form element (like a <div> or <p>).
OverthereAuthor Commented:
I understand. I don't think sending the value of the textfield as part of the url string would be a good idea simply because it will contain html code and mostly because it could be very large. The whole purpose of the child page is to render the coding as if it was a web page. Any more thoughts anyone?
hieloCommented:
>>simply because it will contain html code
I don't know what you mean by that, but the suggestion given encodes the data using encodeURIComponent() first, so there will be no collision between data and special url characters - ex "=".

>>mostly because it could be very large.
That is a valid point.  I thought you were editing html fragments (like a "small" div).  Knowing that you are dealing with large content makes a difference.

I suggest that you don't "pass" anything:
<script type="text/javascript" language="javascript">
    function mkPreview()     
        {
	    window.open('preview.html', 'Preview', 'width=600, height=600,left=70, top=70 scrollbars=yes resizable=yes menubar=no');
     }
</script>

Open in new window


Then in preview.html, you need to "reach into" the parent window and "retrieve" the desired value:
<script type="text/javascript">
/*
//forms[0] refers to the first <form> element on the page.  Thus, if you have TWO forms:
//    <form ><!-- this form is to do site search --></form>
//   <form ><!-- this form is your application's form --></form>
// given the order in which the <forms> are defined above, since the application form
// is defined second, then you would need to use forms[1] (forms is a zero based collection of 
// references to <form> elements.)
// If there is only one <form> on the page, then use forms[0].
*/
document.write( window.opener.document.forms[0].supoffers.value );
</script>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
OverthereAuthor Commented:
I understand, sometimes its hard to verbalize in written form what one is trying to communicate.  I never knew that about forms. Interesting.
 Question, in referencing the forms[0], can the name of the actual page be a substitute for forms[0] as in the example below? I am going to give the code a try. More later and thank you.
document.write( window.opener.document.savoffer.php.supoffers.value );

Open in new window

hieloCommented:
>> can the name of the actual page be a substitute for forms[0]
No.  The name of the file has no bearing in the DOM tree.  If you don't know anything about DOM, do yourself a favor and read up on it.  There should be plenty of articles out there on the subject.  IMHO, understanding the DOM is essential to front end web development.

Given:
<form name="myForm" id="f1" method="post" action="#">
<table  align="center">
            <tr><td><textarea id="myhtml" name="supoffers" cols="80" rows="20"></textarea></td></tr>
        </table>
</form>

from the popup you could retrieve the value of supoffers by using the form's:
- id:
window.opener.document.forms["f1"].supoffers.value OR
window.opener.document.getElementById("f1").supoffers.value

- name:
window.opener.document.myForm.supoffers.value OR
window.opener.document.forms["myForm"].supoffers.value OR
window.opener.document.getElementsByName("myForm")[0].supoffers.value

- index position of the form in the document as previously mentioned:
window.opener.document.forms[0].supoffers.value;

If you have multiple fields, you can first store a reference to the form onto a variable and use that as a "shortcut" to dereference the fields - ex:
var the_form = window.opener.forms["f1"];

// assuming you also have <input name="firstName"/><input name="lastName"/> in the <form>
document.write( the_form.firstName.value);
document.write( the_form.lastName.value);
document.write( the_form.supoffers.value);

Open in new window

OverthereAuthor Commented:
Thank you very much and yes, I need to have a better understanding of DOM. Your suggestion worked well, solved the problem. And I thank you for taking the extra time to further explain. I would also like to thank everyone who contributed.
OverthereAuthor Commented:
Thanks again. and thank you to everyone who responded.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.