Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a variable with JavaScript that PHP can recognize?

I have a series of PHP statements that I only want to run if javaScript is enabled.

if($js_enabled == 'yes') {
   //Run a series of PHP statements
}

My problem is that I want to create that $js_enabled variable with javaScript. Therefore, if javaScript is enabled, the variable will be created and the PHP statements will be run, but if javaScript is not enabled, the variable will never be created and the PHP statements will not run.

How can I create a variable with JavaScript that PHP can recognize?

like image 282
zeckdude Avatar asked Aug 29 '26 08:08

zeckdude


1 Answers

You can do

$browser = get_browser();
if ($browser['javascript'] == 1) {
    // your code here
}

Please read the documentation for get_browser for caveats, especially

Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system. browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here. While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

Also checkout the link given in the comments to get_browser:

  • http://code.google.com/p/phpbrowscap/

EDIT As you correctly point out in the comments, the above will not tell you if JavaScript is enabled but just whether the browser is capable of running it. Finding out about the clientside from the serverside is impossible, because the serverside runs first. If anything, inform the serverside after a page has been served, e.g. like @mck89 suggested or simply set a cookie you can read on each subsequent request.

But generally speaking, if your site requires JavaScript enabled, you should simply add a message to inform the user about this requirement, e.g.:

<noscript>This page requires JavaScript to run properly</noscript>

In other words, don't check from PHP. Just set every variables the browser might use, if JavaScript is enabled and consider using graceful degradation or progressive enhancement.

like image 81
Gordon Avatar answered Aug 30 '26 20:08

Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!