Skip to content Skip to sidebar Skip to footer

Javascript Variable In PHP

Using the HTML5 Geolocation API I've ended up with some variables in Javascript that I need to pass to PHP in order to continue. My code is below, how could it be achieved? I've tr

Solution 1:

Considering Javascript is interpreted by the client only after the server interprets the PHP, this is impossible.

Your only way to pass the Javascript data to PHP and then show the PHP results would be to send the data retrieved by the Javascript to the PHP via AJAX/XHR and then use Javascript to display the response from the PHP script.


Solution 2:

To pass javascript variables to PHP you will have no choice but to request a new page, since PHP stops executing when a page is sent to the browser.

You can pass to it either via GET, POST or COOKIE. GET is the easiest way: http://domain.com/page?town=XYZ. All you need to do afterwards is store your town in a PHP session and redirect to the desired page using header('Location: http://domain.com/page')

Using an Ajax request will allow you to do that without resorting to sessions and page reloads.


Solution 3:

You are mixing Server-side scripting along with browser-side scripting

$variable dissapears on the browser-side and so it will always hold "document.write(variable);" whatever the script inside there is written in.

You can however use AJAX to send the data back to php & process it there.


Post a Comment for "Javascript Variable In PHP"