Returning a php variable to Javascript.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • CpVermont
    New Member
    • Feb 2008
    • 14

    #1

    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.

    Code:
       print"<script type='text/javascript'>parent.myFunction.call(".$myPhpVar.");</script>";
       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
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    Do js arguments need to be in quotes?
    [php]
    echo "<js stuff...(\"argu ment1\", \"".$_arg2." \") ... ";
    [/php]

    Comment

    • eddierosenthal
      New Member
      • Jan 2008
      • 11

      #3
      Originally posted by CpVermont
      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.

      Code:
         print"<script type='text/javascript'>parent.myFunction.call(".$myPhpVar.");</script>";
         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.
      [code=html]
      <script type="text/javascript">
      <!--
      var http = createRequestOb ject();

      function createRequestOb ject() {
      var xmlhttp;
      try { xmlhttp=new ActiveXObject(" Msxml2.XMLHTTP" ); }
      catch(e) {
      try { xmlhttp=new ActiveXObject(" Microsoft.XMLHT TP");}
      catch(f) { xmlhttp=null; }
      }
      if(!xmlhttp&&ty peof XMLHttpRequest! ="undefined" ) {
      xmlhttp=new XMLHttpRequest( );
      }
      return xmlhttp;
      }
      // -->
      </script>
      <script type="text/javascript">
      <!--
      function sendRequestText Post(name, value,cf,room) {



      var rnd = Math.random();
      //if ( name == 'email' )
      // alert (" name is \n" + name + " value is:\n " + value );

      try{
      http.open('POST ', 'handle_form.ph p');
      http.setRequest Header('Content-Type', 'application/x-www-form-urlencoded');
      http.onreadysta techange = handleResponseT ext;
      http.send('name ='+name+'&value ='+value+'&cf=' +cf+'&room='+ro om+'&rnd='+rnd) ;

      }
      catch(e){}
      finally{}
      }
      // -->
      </script>

      <script type="text/javascript">
      <!--
      function handleResponseT ext() {
      try{
      if((http.readyS tate == 4)&& (http.status == 200)){
      var response = http.responseTe xt;
      document.getEle mentById("idfor results").inner HTML = response;
      //alert(" handled " );
      }
      }
      catch(e){alert( "hello");}
      finally{}
      }
      // -->
      </script>

      <script type="text/javascript">
      <!--

      //document.getEle mentById("text1 ").focus();
      // return false;
      //setTimeout(func tion(){field.fo cus()}, 10);
      // document.getEle mentById("email ").focus();

      function validate_email( )
      {
      var r = document.form1. email.value;
      var at = r.indexOf('@',0 );
      var dot = r.lastIndexOf(" .");
      var a_space = r.indexOf(" ");
      var len = r.length -1;
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var myemail= document.getEle mentById("email ");

      if ( a_space != -1 ) {
      alert ( "Please enter good email address, thanks! ( space)" );
      setTimeout(func tion(){myemail. focus()}, 10);
      //document.getEle mentById("email ").focus();
      return false;
      }

      if ( at == -1 ) {
      alert ( "Please enter good email address, thanks! ( no @ sign)" );
      setTimeout(func tion(){myemail. focus()}, 10);
      return false;
      }
      if ( dot == -1 ) {
      alert ( "Please enter good email address, thanks! ( no dot)" );
      setTimeout(func tion(){myemail. focus()}, 10);
      return false;
      }

      if (r.length < 5){
      alert ( "Please enter good email address, thanks! (too short)" );
      setTimeout(func tion(){myemail. focus()}, 10);
      return false;
      }

      //alert (" dot is " + dot + " len is " + len );
      if ( dot == len ) {
      alert ( "Please enter good email address, thanks! (nothing after dot)" );
      setTimeout(func tion(){myemail. focus()}, 10);
      return false;
      }
      if ( (len - dot ) <=2 ) {
      alert ( "Please enter good email address, thanks! (hardly anything after dot)" );
      setTimeout(func tion(){myemail. focus()}, 10);
      return false;


      }

      if (!filter.test(r )) {
      alert('Required ! correct email address');
      setTimeout(func tion(){myemail. focus()}, 10);
      return false;
      }

      var el = document.getEle mentById('gener al');
      //el.style.backgr oundColor = 'red';
      el.style.displa y="block";
      el = document.getEle mentById('email ');
      sendRequestText Post(el.name,el .value,0,'GENER AL');

      }
      // -->
      </script>
      </head>
      <body onload="form1.e mail.focus();">
      <h3> Your information is important to us and privileged information. It will be used for contacting you only.</h3>
      <form name="form1" id="form1" action="<? $_SERVER[’PHP_SELF’] ?>" method="post">
      <div id="formheader" >
      General Information <div id="idforresult s"></div>
      <table id="generaltabl e" bgcolor="#FF663 3" width="93%" border="2" cellspacing="5" >
      <tr>
      <td width="8%">*E-mail</td>
      <td width="23%">
      <input name="email" id="email" onblur="validat e_email()" type="text" size="25"
      />
      </td>
      <td width="10%">Nam e </td>
      <td width="27%">
      <input name="name" type="text" size="35" onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" />
      </td>
      <td width="9%">Home Phone</td>
      <td width="15%">
      <input name="homephone " type="text" value="" size="14"
      onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" />
      </td>
      </tr>
      <tr>
      <td width="10%">Cel l Phone </td>
      <td>
      <input name="cell" type="text" value="" size="14"
      onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" />
      </td>
      <td>Referral</td>
      <td><select name="referral" onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" >
      <option value="SelectOn e">Select One</option>
      <option value="Real Estate Agent">Real Estate Agent</option>
      <option value="Friend"> Friend</option>
      <option value="Newspape r">Newspaper </option>
      <option value="Internet ">Internet</option>
      <option value="Radio">R adio</option>
      <option value="TV" >TV</option>
      <option value="Truck Signage" >Truck Signage</option>
      <option value="Neighbor " >Neighbor</option>
      <option value="Flyer" >Flyer</option>
      <option value="Coupon" >Coupon</option>
      <option value="Business Card" >Business Card</option>
      </select>
      </td>
      <td>Date of Move</td>
      <td>
      <input name="move_dt" type="text" size="14" />
      <script type="text/javascript" language=javasc ript>
      var mycal = new calendar("FIELD :document.form1 .move_dt;MOVEMO DE:2;DIR:primor is;YEAR:2;MONTH :2;FORMAT:2;DEL IMITER:-;FUNCTION:showD ate;");
      mycal.writeCale ndar();
      </script>
      </td>
      </tr>
      <tr>
      <td>Type of Move </td>
      <td><select name="move_typ" size=1 onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" >
      <option value="Select One">Select One</option>
      <option value="resident ial">residentia l</option>
      <option value="commerci al">commercia l</option>
      </select>
      </td>
      <td >From Zip Code:</td>
      <td><input type="text" name="from_zip" value="" size="10"
      onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" /> </td>
      <td >To Zip Code:</td>
      <td><input type="text" name="to_zip" value="" size="10"
      onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" /> </td>
      </tr >
      <tr>
      <td >Number of Rooms:</td>
      <td><select name="num_rooms " onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" />
      <script type="text/javascript">
      var i = 1;
      while ( i <= 45 ) {
      document.write( '<option value=' + i + '>' + i + '</option>');
      i++;
      }
      document.write( '</select>');
      </script>
      </td>
      <td >Number of floors:</td>
      <td><select name="num_level s" onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" />
      <script type="text/javascript">
      var i = 1;
      while ( i <= 25 ) {
      document.write( '<option value=' + i + '>' + i + '</option>');
      i++;
      }
      document.write( '</select>');
      </script>
      </td>
      <td >Elevator:</td>
      <td><select name="elevator" onchange="sendR equestTextPost( this.name,this. value,0,'GENERA L')" >
      <option value="0">Selec t One</option>
      <option value="yes">yes </option>
      <option value="no">no</option>
      </select>
      </td>
      </tr>
      </table>
      </div>
      <div align="left">* required<br />
      </div>
      <ul>
      <li>
      <div id="general" align="center" >
      <a href="living-room-form.html">Next To Living Room (please fill out as much as you can first)</a>
      </div>
      </li>
      </ul>
      </form>
      </body>
      </html>[/code]
      Last edited by ronverdonk; Feb 27 '08, 05:12 PM. Reason: code within appripriate tags

      Comment

      • Markus
        Recognized Expert Expert
        • Jun 2007
        • 6092

        #4
        USE CODE TAGS!

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

        Comment

        • ronverdonk
          Recognized Expert Specialist
          • Jul 2006
          • 4259

          #5
          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

          Comment

          • eddierosenthal
            New Member
            • Jan 2008
            • 11

            #6
            Originally posted by markusn00b
            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.

            Comment

            • Markus
              Recognized Expert Expert
              • Jun 2007
              • 6092

              #7
              Originally posted by eddierosenthal
              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.

              Comment

              • CpVermont
                New Member
                • Feb 2008
                • 14

                #8
                Originally posted by markusn00b
                @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!

                Comment

                • Markus
                  Recognized Expert Expert
                  • Jun 2007
                  • 6092

                  #9
                  Originally posted by CpVermont
                  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.
                  [code=javascript]
                  function doSomething(var _1, var_2)
                  {
                  alert(var_1 + var_2);
                  }
                  [/code]
                  [code=html]
                  <body onload="doSomet hing("<?php echo $_var1;?>", "<?php echo $_var2;?>");">
                  [/code]

                  Comment

                  • eddierosenthal
                    New Member
                    • Jan 2008
                    • 11

                    #10
                    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

                    [code= text]
                    document.getEle mentById( )
                    [/code]

                    function to get the value.
                    hth
                    Last edited by eddierosenthal; Mar 2 '08, 05:19 PM. Reason: wrong answer

                    Comment

                    Working...