2

Possible Duplicate:
How to pass JS variable to php?
pass a js variable to a php variable

I'm passing a javascript from a script to an html page using document.getElementById.innerHTML. The value is printed out correctly in my html page...Now I would know it is possible take this value print in html page and (always in the same page) put it in a php variable?

Community
  • 1
  • 1
eng_mazzy
  • 1,049
  • 4
  • 23
  • 39
  • 1. PHP runs on the server. Generates HTML code that is sent to the browser. 2. Javascript runs in the browser. You cannot really put something in a PHP variable that is generated in this step, because PHP has long finished running. – kapa Feb 21 '12 at 11:17

4 Answers4

5

Create a hidden variable like this

<form method="post">
      <input type="hidden" name="hiddenField" id="hiddenField"/>
</form>

in Javascript set value for that variable

document.getElementById("hiddenField").value=6;

in PHP

$value=$_POST['hiddenField'];
Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36
0

If you want to call back to a PHP script from your page, you'll have to look into XMLHttpRequest (or a wrapper library such as jQuery).

http://en.wikipedia.org/wiki/Ajax_%28programming%29

James M
  • 18,506
  • 3
  • 48
  • 56
0

After you see a page, the php script finished, so you can only send a var via Ajax to your php file and run the script again.

one easy way to use ajax is jquery

Neysor
  • 3,893
  • 11
  • 34
  • 66
0

I can think of two ways to do this:

Use an XMLHttpRequest object to send an asynchronous request to some PHP page which records this value.

On the php [holdvalue.php] side:

<?php
    $myval = $_GET['sentval'];
    // Do something with $myval
?>

On the JavaScript side:

var x = 34; //Some interesting value
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "holdvalue.php/?sentval=" + x, true);
xmlhttp.send();

OR, Use a hidden form field. On the HTML side:

<form id="sendform" method="get" action="holdvalue.php">
 <input type="hidden" id="sentval" />
 <input type="submit" />
</form>

And on the JS side: document.getElementById("sentval").value = x; // Either the following or send it whenever the user submits the form: document.getElementById("sendform").submit();

Rohan Prabhu
  • 7,180
  • 5
  • 37
  • 71