27

I need to access a JavaScript variable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:

<script type="text/javascript" charset="utf-8">
    var test = "tester";
</script>

<?php
    echo $_GET['test'];
?>

I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.

UPDATE: OK, I guess I simplified that too much. What I'm trying to do is create a form that will update a Twitter status when submitted. I've got the form working OK, but I want to also add geolocation data. Since I'm using Javascript (specifically, the Google Geolocation API) to get the location, how do I access that information with PHP when I'm submitting the form?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Armstrong
  • 3,585
  • 12
  • 42
  • 47

9 Answers9

36

The short answer is you can't.

I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).

You're doing a $_GET, which is used to retrieve form values:

The built-in $_GET function is used to collect values in a form with method="get".

In other words, if on your page you had:

<form method="get" action="blah.php">
    <input name="test"></input>
</form>

Your $_GET call would retrieve the value in that input field.

So how to retrieve a value from JavaScript?

Well, you could stick the javascript value in a hidden form field...

<script type="text/javascript" charset="utf-8">
    var test = "tester";
    // find the 'test' input element and set its value to the above variable
    document.getElementByID("test").value = test;
</script>

... elsewhere on your page ...

<form method="get" action="blah.php">
    <input id="test" name="test" visibility="hidden"></input>
    <input type="submit" value="Click me!"></input>
</form>

Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.

Pandincus
  • 9,506
  • 9
  • 43
  • 61
  • Thanks, I've updated my question to clarify what I'm trying to achieve. Do you think the above solution (invisible form field) is still the best solution? – Chris Armstrong Feb 26 '10 at 01:51
  • 2
    You could also use XHR to load your page and put the get variables in yourself. This would remove the form submitting... basiclaly, you would load the url "asdf.php?test="+test.value – Warty Feb 26 '10 at 03:14
  • 1
    @Chris Armstrong Sure, it's a fine solution. However, I don't know how much data that is, and I _believe_ that GET requests have a limit of about 2kb of data (not researched, just an assumption). Youmay want to consider using a POST instead of a GET to send your form data. Additionally, this way the data won't appear in the URL field of the browser. Something else to consider - you may set the geolocation data when the page loads, but what if the user is in a different place when they click 'submit'? In this case, you may want to use javascript to submit the form: http://bit.ly/qOEhx – Pandincus Feb 27 '10 at 01:34
  • The invisible form field does seem to be working fine, and the geolocation data is only two coordinates so size shouldn't be a problem, however I am looking at using ajax (specifically, jquery) to submit the form, so do you think I'd be better waiting till the user hits submit before looking for their location? – Chris Armstrong Feb 27 '10 at 18:21
  • @Chris Armstrong jquery is a great choice, and absolutely I think it would be better to use a regular button instead of the form submit button, use jquery to bind a function to the button's "click" event, and at that point capture the geolocation and then use javascript to submit the form. – Pandincus Feb 28 '10 at 21:42
  • What is blah.php? Is that the name of the current document? – node ninja Mar 06 '12 at 20:52
4

As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.

If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax

Decipher
  • 516
  • 3
  • 5
2

_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:

<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
    var test = "<?php echo $test?>";
</script>

<?php
    echo $test;
?>

Of course, I don't know why you want this, so I'm not sure the best solution.

EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
2

If showing data to the user, do a redirect:

<script language="JavaScript">
    var tester = "foobar";
    document.location="http://www.host.org/myphp.php?test=" + tester;
</script>

or an iframe:

<script language="JavaScript">
    var tester = "foobar";
    document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>

If you don't need user output, create an iframe with width=0 and height=0.

Hawkcannon
  • 227
  • 3
  • 8
2

try adding this to your js function:

    var outputvar = document.getElementById("your_div_id_inside_html_form");
    outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';

Later in html:

    <div id="id_you_choosed_for_outputvar"></div>

this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.

In your specific geolocation case you can try adding the following to function showPosition(position):

    var outputlon = document.getElementById("lon1");
    outputlon.innerHTML = '<input id=lon value='+lon+'>';
    var outputlat = document.getElementById("lat1");
    outputlat.innerHTML = '<input id=lat value='+lat+'>';  

later add these div to your html form:

<div id=lat1></div>
<div id=lon1></div>

In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.

Hope this will help.

cosphi
  • 101
  • 5
1

Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:

// -- index.php

<?php
  if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">  
  var d = new Date(); 
  var timezoneOffset = d.getTimezoneOffset() / 60;
  // the cookie expired in 3 hours
  d.setTime(d.getTime()+(3*60*60*1000));
  var expires = "; expires="+d.toGMTString();
  document.cookie = "timezone=" +  timezoneOffset + expires + "; path=/";
  document.location.href="index.php"
</script>
</html>
<?php
} else {
  ?>

  <html>
  <head>
  <body>

  <?php 
  if(isset($_COOKIE['timezone'])){ 
    dump_var($_COOKIE['timezone']); 
  } 
}
?>
kyle
  • 11
  • 1
0

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

Leonidas
  • 2,440
  • 15
  • 22
0

I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?

-1
<script type="text/javascript">
    function gotzpl(){
        var query = window.location.search.substring(1);
        if(query){
        }else{
            var timez = Intl.DateTimeFormat().resolvedOptions().timeZone;
            if(timez != 'undefined'){
            window.location = "https://sks.com/searches.php?tzi="+timez;
            }
        }
    }
</script>
<?php 
    // now retrieve value from URL and use it in PHP; 
    // This way you can get script value in PHP
    $istzg = $_GET['tzi'];
?>
<body onload="gotzpl()">