By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,829 Members | 2,308 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,829 IT Pros & Developers. It's quick & easy.

Returning a php variable to Javascript.

P: 14
Good day All,

I am trying, with no success obviously, to return the value in $myPhpVar to a javascript function. I've tried the following and many other combinations using echo and printf.

Expand|Select|Wrap|Line Numbers
  1.    print"<script type='text/javascript'>parent.myFunction.call(".$myPhpVar.");</script>";
  2.    print"<script type='text/javascript'>parent.myFunction.call($myPhpVar);</script>";
I'm using a hidden iframe to post form data after javascript validates it. This saves calls to my server, and keeps the feel of the page smooth because there is no refresh after submit. I would like to return the stats of the serverside processing to the javascript function that closes the iframe. Right now I save the results then call my server using a xmlhttp request object to retrieve them. Not very efficient to say the least. Your help is greatly appreciated!

Thanks,
CpVermont
Feb 26 '08 #1
Share this Question
Share on Google+
9 Replies


Markus
Expert 5K+
P: 6,050
Do js arguments need to be in quotes?
[php]
echo "<js stuff...(\"argument1\", \"".$_arg2."\") ... ";
[/php]
Feb 26 '08 #2

P: 11
Good day All,

I am trying, with no success obviously, to return the value in $myPhpVar to a javascript function. I've tried the following and many other combinations using echo and printf.

Expand|Select|Wrap|Line Numbers
  1.    print"<script type='text/javascript'>parent.myFunction.call(".$myPhpVar.");</script>";
  2.    print"<script type='text/javascript'>parent.myFunction.call($myPhpVar);</script>";
I'm using a hidden iframe to post form data after javascript validates it. This saves calls to my server, and keeps the feel of the page smooth because there is no refresh after submit. I would like to return the stats of the serverside processing to the javascript function that closes the iframe. Right now I save the results then call my server using a xmlhttp request object to retrieve them. Not very efficient to say the least. Your help is greatly appreciated!

Thanks,
CpVermont
you said you were using http object to post to php on server side - that means the results you have calculated are available to the object as responsetext or response xml - in your case you are posting to text object so any thing echoed is forwarded to client via the response text. ie ; here is some html with a form on it making call to a php form handler - the 'handler.php' echoes back to the area of the form called idresults - you can use that and parse it using javascript, even though it originated from a php file hanler.
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2. <!--
  3.     var http = createRequestObject();
  4.  
  5.     function createRequestObject() {
  6.         var xmlhttp;
  7.         try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
  8.       catch(e) {
  9.         try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
  10.         catch(f) { xmlhttp=null; }
  11.       }
  12.       if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
  13.           xmlhttp=new XMLHttpRequest();
  14.       }
  15.         return  xmlhttp;
  16.     }
  17.  // -->
  18. </script>
  19. <script type="text/javascript">
  20. <!--
  21.     function sendRequestTextPost(name, value,cf,room) {
  22.  
  23.  
  24.  
  25.     var rnd = Math.random();
  26.     //if ( name == 'email' ) 
  27.     //     alert (" name is \n" + name  + " value is:\n " + value ); 
  28.  
  29.     try{
  30.     http.open('POST',  'handle_form.php');
  31.     http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  32.     http.onreadystatechange = handleResponseText;
  33.         http.send('name='+name+'&value='+value+'&cf='+cf+'&room='+room+'&rnd='+rnd);
  34.  
  35.     }
  36.     catch(e){}
  37.     finally{}
  38. }
  39.  // -->
  40. </script>
  41.  
  42. <script type="text/javascript">
  43. <!--
  44. function handleResponseText() {
  45.     try{
  46.     if((http.readyState == 4)&& (http.status == 200)){
  47.         var response = http.responseText;
  48.         document.getElementById("idforresults").innerHTML = response;
  49.        //alert(" handled " );
  50.         }
  51.   }
  52.     catch(e){alert("hello");}
  53.     finally{}
  54. }
  55.  // -->
  56. </script>
  57.  
  58. <script type="text/javascript">
  59. <!--
  60.  
  61. //document.getElementById("text1").focus();
  62. //                return false; 
  63.     //setTimeout(function(){field.focus()}, 10);
  64.     // document.getElementById("email").focus(); 
  65.  
  66. function validate_email(  ) 
  67. {
  68.   var  r = document.form1.email.value;
  69.   var at = r.indexOf('@',0);
  70.   var dot = r.lastIndexOf(".");
  71.   var a_space = r.indexOf(" ");
  72.   var len = r.length -1;
  73.   var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  74.  
  75.   var myemail= document.getElementById("email"); 
  76.  
  77.          if ( a_space != -1  ) {
  78.           alert ( "Please enter good email address, thanks! ( space)" );
  79.           setTimeout(function(){myemail.focus()}, 10);
  80.           //document.getElementById("email").focus();   
  81.           return false;
  82.        }
  83.  
  84.        if ( at == -1  ) {
  85.           alert ( "Please enter good email address, thanks! ( no @ sign)" );
  86.           setTimeout(function(){myemail.focus()}, 10);
  87.           return false;
  88.        }
  89.        if ( dot == -1  ) {
  90.           alert ( "Please enter good email address, thanks! ( no dot)" );
  91.           setTimeout(function(){myemail.focus()}, 10);
  92.           return false;
  93.        }
  94.  
  95.        if (r.length < 5){
  96.            alert ( "Please enter good email address, thanks! (too short)" );
  97.            setTimeout(function(){myemail.focus()}, 10);
  98.            return false;
  99.         } 
  100.  
  101.         //alert (" dot is " + dot + " len is " + len );
  102.        if ( dot == len ) {
  103.            alert ( "Please enter good email address, thanks! (nothing after dot)" );
  104.            setTimeout(function(){myemail.focus()}, 10);
  105.            return false;
  106.        }
  107.        if ( (len - dot ) <=2 ) {
  108.            alert ( "Please enter good email address, thanks! (hardly anything after dot)" );
  109.            setTimeout(function(){myemail.focus()}, 10);
  110.           return false;
  111.  
  112.  
  113.        }
  114.  
  115.       if (!filter.test(r)) {
  116.               alert('Required! correct email address');
  117.              setTimeout(function(){myemail.focus()}, 10);
  118.              return false;
  119.             }
  120.  
  121.         var el = document.getElementById('general');
  122.         //el.style.backgroundColor = 'red';    
  123.         el.style.display="block";
  124.         el = document.getElementById('email');
  125.         sendRequestTextPost(el.name,el.value,0,'GENERAL');
  126.  
  127. }
  128.  // -->
  129. </script>
  130. </head>
  131. <body onload="form1.email.focus();">
  132. <h3> Your information is important to us and privileged information. It  will be used for contacting you only.</h3>
  133. <form name="form1" id="form1" action="<? $_SERVER[’PHP_SELF’] ?>"  method="post">
  134. <div id="formheader">
  135.     General Information <div id="idforresults"></div>
  136.   <table id="generaltable" bgcolor="#FF6633" width="93%" border="2" cellspacing="5">
  137.     <tr>
  138.        <td width="8%">*E-mail</td>
  139.       <td width="23%">
  140.        <input name="email" id="email" onblur="validate_email()" type="text"  size="25" 
  141.          />   
  142.       </td>
  143.       <td width="10%">Name </td>
  144.       <td width="27%">     
  145.        <input  name="name"   type="text" size="35"  onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />          
  146.       </td>
  147.       <td width="9%">Home Phone</td>
  148.       <td width="15%">
  149.        <input name="homephone"   type="text" value=""  size="14"       
  150.         onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />   
  151.       </td>
  152.     </tr>
  153.         <tr>
  154.       <td width="10%">Cell Phone </td>
  155.       <td>     
  156.        <input name="cell"   type="text" value=""  size="14"  
  157.         onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />          
  158.       </td>
  159.        <td>Referral</td>
  160.          <td><select name="referral" onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" >
  161.          <option value="SelectOne">Select One</option>
  162.          <option value="Real Estate Agent">Real Estate Agent</option>
  163.         <option value="Friend">Friend</option>
  164.         <option value="Newspaper">Newspaper </option>
  165.         <option value="Internet">Internet</option>
  166.         <option value="Radio">Radio</option>
  167.         <option value="TV" >TV</option>
  168.         <option value="Truck Signage" >Truck Signage</option>
  169.         <option value="Neighbor" >Neighbor</option>
  170.         <option value="Flyer" >Flyer</option>
  171.         <option value="Coupon" >Coupon</option>
  172.         <option value="Business Card" >Business Card</option>
  173.       </select>
  174.       </td>
  175.             <td>Date of Move</td>
  176.         <td>
  177.        <input name="move_dt"   type="text"  size="14"   />
  178.            <script type="text/javascript" language=javascript>
  179.             var mycal = new calendar("FIELD:document.form1.move_dt;MOVEMODE:2;DIR:primoris;YEAR:2;MONTH:2;FORMAT:2;DELIMITER:-;FUNCTION:showDate;");
  180.             mycal.writeCalendar();
  181.            </script> 
  182.       </td>
  183.     </tr>
  184.     <tr>
  185.           <td>Type of Move </td>
  186.           <td><select  name="move_typ" size=1 onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" > 
  187.                <option value="Select One">Select One</option>
  188.                <option value="residential">residential</option>
  189.                <option value="commercial">commercial</option>
  190.                </select>
  191.           </td>
  192.       <td >From Zip Code:</td>
  193.       <td><input type="text" name="from_zip" value="" size="10"
  194.        onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />    </td>
  195.       <td >To Zip Code:</td>
  196.       <td><input type="text" name="to_zip" value="" size="10" 
  197.        onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />   </td>
  198.     </tr >
  199.     <tr>
  200.       <td >Number of Rooms:</td>
  201.       <td><select  name="num_rooms"  onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />  
  202.             <script type="text/javascript">
  203.                 var i = 1;
  204.                 while ( i <= 45 ) {
  205.                    document.write('<option value=' + i + '>' + i + '</option>');
  206.                     i++;
  207.                 }
  208.                 document.write('</select>');
  209.             </script>      
  210.                 </td>
  211.        <td >Number of floors:</td>
  212.       <td><select  name="num_levels"  onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" />  
  213.             <script type="text/javascript">
  214.                 var i = 1;
  215.                 while ( i <= 25 ) {
  216.                    document.write('<option value=' + i + '>' + i + '</option>');
  217.                     i++;
  218.                 }
  219.                 document.write('</select>');
  220.             </script>      
  221.        </td>
  222.       <td >Elevator:</td>
  223.         <td><select name="elevator" onchange="sendRequestTextPost(this.name,this.value,0,'GENERAL')" >
  224.          <option value="0">Select One</option>
  225.          <option value="yes">yes</option>
  226.         <option value="no">no</option>
  227.       </select>
  228.       </td>
  229.     </tr>    
  230.   </table>
  231.  </div>
  232.   <div align="left">* required<br /> 
  233.   </div>
  234.    <ul>
  235.    <li>
  236.      <div   id="general" align="center" >
  237.              <a href="living-room-form.html">Next To Living Room (please fill out as much as you can first)</a> 
  238.       </div>
  239.    </li>
  240.  </ul>
  241. </form>
  242. </body>
  243. </html>
Feb 27 '08 #3

Markus
Expert 5K+
P: 6,050
USE CODE TAGS!

It's inconveinient to look through that code when it's not wrapped in [code=php] code goes here... [/code] tags.
Feb 27 '08 #4

ronverdonk
Expert 2.5K+
P: 4,258
eddierosenthal: I for sure are not going to read that mess bunch of code.

If you want anyone to seriously look at your code, then you should make it a bit easier for our members to help you. One of these is to enclose any code shown within the appropriate code tags. Read the Posting Guidelines before you continue.

moderator
Feb 27 '08 #5

P: 11
USE CODE TAGS!

It's inconveinient to look through that code when it's not wrapped in [code=php] code goes here... [/code] tags.
I'm a newbie here so be extra sweet.
you are saying that i should type :
"Code: ( text )" before the script? Please explain how does that affect the look of code? (From the looks of my browser the script looks the same to me as it normally does, without code tags)
I believe a more helpful response to a post such as this:
1) give a link to the required code tag policy
2) forum technology management would have allowed me to edit back corrections to suit the policy
3) Point out good examples in the reading material
4) code tags do not change the fact that if the could truly was messy it would not making reading more pleasurable.
Feb 27 '08 #6

Markus
Expert 5K+
P: 6,050
I'm a newbie here so be extra sweet.
you are saying that i should type :
"Code: ( text )" before the script? Please explain how does that affect the look of code? (From the looks of my browser the script looks the same to me as it normally does, without code tags)
I believe a more helpful response to a post such as this:
1) give a link to the required code tag policy
2) forum technology management would have allowed me to edit back corrections to suit the policy
3) Point out good examples in the reading material
4) code tags do not change the fact that if the could truly was messy it would not making reading more pleasurable.
@4
It DOES make it easier to read code, when the code is wrapped in code tags. Why do you think code tags are provided? For the sake of it? No. To make the code readable.
@2 you are expected to READ THE FORUM GUIDELINEs before posting - this is forum ettiqutte.
@1 if you were to have read the forum guidelines (a sticky on every page) you would know how to post code.
Feb 27 '08 #7

P: 14
@4
It DOES make it easier to read code, when the code is wrapped in code tags. Why do you think code tags are provided? For the sake of it? No. To make the code readable.
@2 you are expected to READ THE FORUM GUIDELINEs before posting - this is forum ettiqutte.
@1 if you were to have read the forum guidelines (a sticky on every page) you would know how to post code.
Sorry about the Code tags thing Y'all. I didn't read the sticky, my bad. But could someone please give me the lowdown on passing the value of a php Variable to a javascript function. (or if it is even possible). Thank you!
Feb 29 '08 #8

Markus
Expert 5K+
P: 6,050
Sorry about the Code tags thing Y'all. I didn't read the sticky, my bad. But could someone please give me the lowdown on passing the value of a php Variable to a javascript function. (or if it is even possible). Thank you!
You just have to echo the variable out into whereever in the script you want it.
Expand|Select|Wrap|Line Numbers
  1. function doSomething(var_1, var_2) 
  2. {
  3.     alert(var_1 + var_2);
  4. }
  5.  
Expand|Select|Wrap|Line Numbers
  1. <body onload="doSomething("<?php echo $_var1;?>", "<?php echo $_var2;?>");">
  2.  
Mar 1 '08 #9

P: 11
sorry i had bad answer, and should read question properly. not only that i should read and parse properly the faq. please forgive and i apologize. Let me know if i am using the code tags properly this time ...

as to getting the problem solved - and i will minimize answer
if you echo the value inside a named 'space' such as an id tag
then the javascript can use the

Expand|Select|Wrap|Line Numbers
  1. document.getElementById( )
  2.  
function to get the value.
hth
Mar 2 '08 #10

Post your reply

Sign in to post your reply or Sign up for a free account.