Is there a way to pass a vairable from javascript to PHP?

If there is, this would be a great help as I would prefer not to have to convert my javascript functions into PHP if possible.

What I'm trying to do is read a cookie using javascript and within the same file use that information in some PHP script.

e.g.

<script language="JavaScript">
$JSvairable = JSfunction(); ### Call a javascript function to read cookie
</script>

<?
if( $PHPvariable = $JSvairable )
{print"$JSvairable";}
else
{print"n/a";}
?>

    • [deleted]

    Why don't you get the cookie value from PHP itself?

    For example lets say your Cookie is named: cactushead and its value is "thevalue",

    then in PHP, just use the variable $cactushead and you can read of its value.

    If you want to set a cookie, use the SetCookie function:

    setcookie("cactushead", "thevalue", time()+3600);

    This will set a cookie with expiry 1 hour from the time it was set. Make sure you call it before printing out anything from the PHP.

    -sridhar

      That wasn't his question.. it seems obvious that he knows how to do a cookie in php but what he was asking (and I want to know), is how to use or get the value of a javascript variable into php.

        server side javascript I know nothing about... and I don't think you could anyway.

        However, if you are talking about client side javascript, I'm there.

        First thing to understand. That JavaScript variable will not be initialized or have any purpose to PHP. Ever. From there, we realize that the JavaScript doesn't get anything done to it on the server... its 100% client side. Which means that you'll have to send another request back to the server with the value of that variable in a form or get encoded url.

        This really doesn't seem to have any value to me since the JavaScript is setting the cookie (right?) which PHP then can read.

        Now, I use alot of hidden forms and such to pass alot of data back and forth between pages, etc. Its a perfect way to do it and JavaScript can handle any programming such as this that needs be done on the client side.

        If this didn't help or apply, then please tell me. πŸ™‚

        -Philip

          Could you please post some code for the way you use hidden forms to pass data from javascript to PHP as I'm mearly a dabbler in both languages.

            • [deleted]

            cactushead,

            What purpose will this provide? Let's just assume PHP is able to access JavaScript variables.

            I.E.
            <script>
            var abc = "sometext";
            </script>

            <?php
            echo $abc;
            ?>

            If this were to work, in what way will you use this? Because like Philip Snyder said, it serves no purpose in the case of cookies since PHP can access it anyway.

            Plus, since PHP is executed BEFORE javascript (client side javascript), what use will it be?

            -sridhar

              5 months later

              I am in the same fix. My reason behind wanting to use a javascript variable in PHP on the same page is this. I'm trying to log info about computers that access my page, in this case I want the screen resolution, and I don't know of any other way to get it than with javascript. I suppose I could just set it to a cookie and then retrieve it with PHP right away but being able to refer to a javascript variable in my PHP would be nice. Any ideas?

                5 days later

                Ok. Here's a simple straight forward explanation of how your web page works (you should already know this if you do PHP).

                1. Client requests web page
                  2.
                  2a. Web server reads page from hard drive
                  2b. Web server parses PHP
                  2c. Web server responds to Client with result(which doesn't necessarily have to be HTML - it can be an image, pdf, or even an mp3 playlist!)
                2. Client's browser displays what was sent from the web server.

                JavaScript doesn't get executed until step 3... which is AFTER the web server parses PHP. SO... a little logic goes a long way here. If you want to grab the user's resolution or browser information, you have to send that in a request to the web server, either in an http cookie or in a form parameter (blah.php?myVar=this).

                IF you need the server to do something with this information before it can show a certain page, you'll need to do 1 of 2 things.

                1. Use a different web page that the user has already visited to store this information
                  OR
                2. Do some REALLY wacky hidden frame control with javascript data transfers

                DO NOT ask me to help you with the 2nd one. I'll simply tell you to do the 1st one. I can personally tell you that the 2nd method DOES work as I have a sweet tree control that I'm working on that dynamically loads X number of levels below the node you click on. That is REALLY funk. Takes alot of JavaScript experience as well as backend coding experience to know how to do that. Also takes alot of time. So no matter how tempting that is, if you don't already have an idea of how you would do it, its NOT for you. πŸ™‚

                -Philip

                  5 days later

                  hi,
                  i need, more complicated thing...
                  first of all, to show the full sized flash banner that is floating over the page, i use external javascript (.js). but, when i try to get path of the swf files form database, i failed. because i don't know how to use php (that is called as javascript from html) to generate js files dynamiclyπŸ™‚)

                  yes, is there any way to do that, (any way) please help me. because of the limitations (and of course different tech's) of sites, i have to use .js (generated by php) to show flash banners that is related with database... but how? if i use <script language=javascript src=xxx.php></script> then how could i design php? have to use header? how?
                  please help...

                  firat bayir

                    2 months later

                    Hello.

                    You mentioned that you use alot of hidden forms.

                    How can forms be 'hidden'? Also, can these forms be invoked without reloading the page.

                    I want the variable that was assigned based on the 'if confirm()' statement to be passed back to a form that has the data fields filled out AND was partially processed on the first 'submit.' I would like the variable from the Javascript routine to now pass that var from the confirm() back to the form to finish processing the form data based on the confirm() var (reloading the form would 'undo' the first part of the form processing.

                    Thank you.

                      2 months later

                      Geez, that's a long way around! Why are you not simply using php for your forms? I know there's lots going on in the programmer's head that we know nothing about as to whys, etc., but if you use <?php echo $form_value ?> in the form, you won't lose the information. It stays there until you force a refresh. Would this help, or is there some reason it MUST be using javascript (other than stubborn pigheadedness, which I often fall victim to ;-).

                      And to the person who says you can't use php in javascript functions I say..."HUH?!?", I do that all the time! If you need code examples, let me know. Of course it helps to know just what exactly it is you're trying to accomplish.

                        Hello.

                        The segment this pertained to was for a Perl project but was going to be used in an upcoming PHP project also. I was trying to take care of both at the same time.

                        I had figured out, (I think) about how to go about it for PHP. I had to totally change the logic for Perl since I did not find a way to accomplish this. I will look at your method.

                        Thanx.

                          3 months later

                          Hi

                          I am trying to set up a shoppping cart for.
                          I need to pass the values that are in
                          <script> GetFormCart()</script> in the php form programn to send the data
                          Everything works fine until the user is going to submit the form.

                          I have the following set up.

                          The user selects the what they want. then they come to the checkout page

                          <HEAD>
                          <TITLE>Order Form</TITLE>
                          <script SRC="nopcart.js"></script>

                          Code.>>>>>>>>>>>>>>

                          then
                          <B><h1><U>Parts & Accessories Order Form</B></h1></U><br>
                          <p><font face="Arial, Helvetica, sans-serif" size="3"><b>The items listed below
                          are currently in your shopping cart: </b></font></p>
                          <FORM ACTION="m.7php" method="POST" onsubmit="return Submitting()" name="FormContacts">
                          <SCRIPT>
                          GetFromCart();
                          </SCRIPT>

                          <TABLE border=0>

                          <TR>
                          <td align=></td>&nbsp;<td align="right"><b>Today's date:</b>&nbsp;&nbsp;<input name = "date" size = "24" value = "Loading..."></td></tr>
                          <tr>
                          <TD>Company Name:</TD>
                          <TD><INPUT NAME="Company" Size=22>&nbsp;&nbsp;&nbsp;&nbsp;Account Number:&nbsp;<INPUT
                          NAME="Account"
                          size="6" MAXLENGTH=6></TD>
                          </TR>
                          <TR>
                          <TD>Contact Name:</TD>
                          <TD><INPUT NAME="Contact_Name" size=25></TD>
                          </TR>
                          <TR>
                          <TD>Purchase Order: </td>
                          <TD><INPUT NAME="Purchase_Order" size=20></TD>
                          </TR>

                          More code...

                          Then when they submit the order, it goes to m7.php

                          See code

                          <?php

                          $msg = "Company:\t$Company\n";
                          $msg .= "Name: \t$First_Name $Last_Name\n";
                          $msg .= "Address:\t$Address\n";
                          $msg .= "City: \t$City\n";
                          $msg .= "State: \t$State\n";
                          $msg .= "Zip Code:\t$Postal_Code\n";
                          $msg .= "Account#:\t$Account\n";
                          $msg .= "Email Address:\t$email\n";

                          $msg .= "Message:\t$message\n\n";

                          $recipient = "whatever.com";
                          $subject = "Web Site Feedback";

                          $mailheaders = "From: My Web Site <> \n";
                          $mailheaders = "Reply-To: $email\n\n";

                          mail($recipient, $subject, $msg, $mailheaders);

                          $msg1 .= "Thanks for placing an Order. We will contact you as soon as possible to inform you regarding your order status and delivery \n\n";

                          However, it doesnt print the values in GetFromCart()

                          How do i pass these values so it would print like the rest. Please if you could help me figure this out.

                          I cant get it to work ..i have tried.

                          I would really appreciate your help thanks..

                          Regards,

                          Al lOpez

                            This is a toughie. I gave up trying to get javascript variables into PHP. It's easy to do it from PHP to javascript, not so easy to do it in reverse. I have seen one method where the person recommends using the document object model to assign the variable to a hidden field in the form. It will then be picked up by the PHP when everything is submitted.

                            A really rough (and possible wrong) example would be in the javascript function do a assignment such as:

                            document.form_name.hidden1 = first_variable;

                            this would assign the value of the first_variable to the hidden field 'hidden1' defined in your form like:

                            <input type="hidden" name="hidden1">

                            The part I'm not quite sure of is if you would have to have one more parameter to the DOM as in :

                            document.form_name.hidden1.value = first_variable;

                            You'll have to play with it and see. AND, I'm not sure if it will work or not. Haven't tried it myself (yet).

                            Good luck, and I'm interested in hearing how it works out, or if anyone else has better ideas or can fine tune this one! I'm also looking for a straight forward treatment of the DOM without launching into esoteric code right off the bat so a person can get a handle on it!

                              Write a Reply...