473,325 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Returning a php variable to Javascript.

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
9 1751
Markus
6,050 Expert 4TB
Do js arguments need to be in quotes?
[php]
echo "<js stuff...(\"argument1\", \"".$_arg2."\") ... ";
[/php]
Feb 26 '08 #2
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
6,050 Expert 4TB
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
4,258 Expert 4TB
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
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
6,050 Expert 4TB
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
@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
6,050 Expert 4TB
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
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

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

Similar topics

1
by: bhavin | last post by:
I want to return an integer value from javascript to my .net code. My javascript returns is : function getIndex() { ---- ---- return (currentIndex); } My C# code is:
7
by: Dr John Stockton | last post by:
What are the best ways of returning multiple results from a subroutine ? I've been using ... return } which is inelegant. I'm used to Pascal's procedure X(const A, B : integer; var C, D :...
3
by: jason | last post by:
I've got this javascript routine (i found on google - thank you) in an asp.net page that on page reload sets the cursor of a textbox to the last line. It works great! Using a similar concept, I...
5
by: Alfonso Morra | last post by:
Hi, What is the recomended way of returning an STL container (e.g. std::string, std::vector etc fom a function? Is it by simply returning a local variable? (I doubt it) std::string...
3
by: Srinivas Aki | last post by:
Hello Everyone, I'm trying to read a dynamic table into an array and then return it back to the php array so that I can register that for the session. I'm not too sure if i'm going in the right...
1
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause...
1
by: bsprogs | last post by:
I am currnetly programming a file hosting website in PHP and I am slowly integrating AJAX into the website. Here is my problem: The user uploads the file. The server processes the file and...
23
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or...
8
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.