Skip to content
Advertisement

How to get JavaScript variable value in PHP

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement