36

I want the value of JavaScript variable which i could access using PHP. I am using the code below but it doesn't return value of that variable in PHP.

// set global variable in javascript
    profile_viewer_uid = 1;

// php code

$profile_viewer_uid=$_POST['profile_viewer_uid']; 

this gives me the following error :-

A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid

Another php code i used which give empty value

$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>

When I echo it shows nothing.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
rash111
  • 1,307
  • 4
  • 19
  • 35
  • Possible duplicate of [Access a JavaScript variable from PHP](https://stackoverflow.com/questions/2338942/access-a-javascript-variable-from-php) – user202729 Jul 28 '18 at 09:12

10 Answers10

25

Add a cookie with the javascript variable you want to access.

document.cookie="profile_viewer_uid=1";

Then acces it in php via

$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
skuntsel
  • 11,624
  • 11
  • 44
  • 67
humbleiam
  • 969
  • 2
  • 12
  • 34
21

You will need to use JS to send the URL back with a variable in it such as: http://www.site.com/index.php?uid=1

by using something like this in JS:

window.location.href=”index.php?uid=1";

Then in the PHP code use $_GET:

$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Chris Cummings
  • 1,538
  • 2
  • 24
  • 39
  • Although on that window.location you'd want to replace the "1" with a bit of code that references the desired variable's value. – Chris Cummings Mar 20 '12 at 17:47
  • 7
    is this possible without redirection – er.irfankhan11 Oct 01 '15 at 13:59
  • I have doubts whether index.php is some arbitrary name that we can put over there or is it a file which needs to be present before we can make that call or is it the name of the file in which we are writing this code itself? (assumming i am writing both html and php in the same file) – Ishan Srivastava Oct 25 '17 at 23:50
  • can you do this with a post instead of a get request? – Jo Momma Nov 22 '21 at 16:07
14

Here is the Working example: Get javascript variable value on the same page.

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>
Arslan Tabassum
  • 900
  • 1
  • 10
  • 25
  • 11
    This code is _NOT_ passing a variable from js to PHP: it's just adding a js script that outputs the variable in the page. – T30 Jan 09 '17 at 14:49
  • 2
    That's what we actually want, without refreshing the page... :) – Arslan Tabassum Oct 19 '17 at 11:42
  • I get your point, but this can be done in pure html/js. Wrapping it in a php echo script is just a "useless" overhead because your php (the script running server side) is still unaware of the variable value. – T30 Oct 19 '17 at 11:55
  • i agree with you... but this is for a rare scenario, in which we need to calculate some value in js first , and then need that value in php for processing... i have gone through that scenario, so this method solve my problem... – Arslan Tabassum Oct 19 '17 at 12:17
  • The problem is that you can't process this variable with php. When php is processing this file (server side), the js variable is not set yet. Js variables are set client side, when php has already run and can't interact anymore, unless you do another http request (for example with [ajax](https://stackoverflow.com/a/46829651/1677209)). – T30 Oct 19 '17 at 14:00
  • @T30 when PHP starts processing it will read JS variable through this code... & ofcourse without another http request... – Arslan Tabassum Jun 28 '19 at 13:57
  • When php processes this script, the js variable is not set yet. Php is executed on the server, and sends the page to the client. The client receives the page, runs the js, and output the variable. But when the client js evaluates the variable, php is not running anymore. – T30 Jun 29 '19 at 14:06
  • Yes, i know. PHP is a server side, JS is a client side... when PHP starts processing... echo ""; this code also processed & get the value that we need without refreshing the page... Basically triggers JS while processing PHP... Please try this out... it will work exactly... I've tried with dynamic variables too... If it didn't work for you...Please let me know i'll share a fiddle too.. – Arslan Tabassum Jul 01 '19 at 08:38
  • PHP can't process javascript, the only thing PHP sees, it's a string containing the – T30 Jul 04 '19 at 13:57
  • Wouldn't the clarifying piece to this argument be to prove it with an incremented number? So like, set var p1=1; Then call a function in javascript (use a button) to increment p1. If you then use the method above, does it echo 1, or 2? Pretty sure it's always 1, as that's what the server knows. – SaintFrag May 03 '21 at 14:33
7

You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.

Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.

If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.

<script type="text/javascript>
    var foo = <?php echo json_encode($somePhpVar); ?>
</script>
floriank
  • 25,546
  • 9
  • 42
  • 66
  • 18
    You do realize that "**can not** communicate" is quite an overstatement, particularly when your very next sentence talks about how to make them communicate. :) – cHao Mar 20 '12 at 15:08
5

If you want to use a js variable in a php script you MUST pass it within a HTTP request.

There are basically two ways:

  • Submitting or reloading the page (as per Chris answer).
  • Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.

A basic example can be:

var profile_viewer_uid = 1;
$.ajax({
  url: "serverScript.php",
  method: "POST",
  data: { "profile_viewer_uid": profile_viewer_uid }
})

And in the serverScript.php file, you can do:

 $profile_viewer_uid = $_POST['profile_viewer_uid'];
 echo($profile_viewer_uid);
 // prints 1

Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.

T30
  • 11,422
  • 7
  • 53
  • 57
  • I created these two files in xampp, but in .php I see: _Warning: Undefined array key "profile_viewer_uid" in C:\xampp\htdocs\zkoska\ppp.php on line 2_ – Davidcz Jul 26 '22 at 14:39
3

PHP runs on the server. It outputs some text. Then it stops running.

The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.

If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.

You can make an HTTP request from JavaScript by using a form or Ajax.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

These are two different languages, that run at different time - you cannot interact with them like that.

PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.

BenOfTheNorth
  • 2,904
  • 1
  • 20
  • 46
1

In your html form make a hidden field

<input type="hidden" id="scanCode" name="SCANCODE"></input>

Then in your javascript update the field value by adding;

document.getElementById("scanCode").setAttribute('value', scanCode);
0

This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself. Given that you have added an php command to catch the variable, you will get it.

-1

You need to add this value to the form data that is submitted to the server. You can use

<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">

inside your form tag.

Shrieks
  • 141
  • 1
  • 6
  • Why so many downvotes? Use JavaScript to change the value of the `input`, then use JavaScript to submit the form? It works, and answers the question! – Elliot Harrell Feb 15 '21 at 13:55