Skip to content Skip to sidebar Skip to footer

Can Php Detect If Javascript Is On Or Not?

I have page which created dynamically. Now I want to add ajax function, so I want to add if statement to change the outputs. if(js is on){ ... ... echo 'js is on'; }else{ ... e

Solution 1:

PHP is executed before any browser action takes place, so no, PHP cannot directly detect whether the user has Javascript on or off.

You must provide a bit more info on what you're doing for us to find you a workaround. In PHP, it is possible to detect whether the call was made via AJAX or not using the $_SERVER['X_HTTP_REQUESTED_WITH'] global variable which jQuery will set automatically.

If you need to show an element when Javascript is enabled, you can first hide the element with CSS and enable it with Javascript/jQuery. The same goes the other way around also.


Solution 2:

You can't do that in PHP because the page is rendered by the time you know. And apart from some crazy redirect scenario, your best bet may be to use CSS + JS to show/hide what you need:

What I normally do (and your mileage may vary depending on what you need to show/hide) is this:

<html>
   <head>
      ... other stuff here, title, meta, etc ...

      <script type="text/javascript">document.documentElement.className += " js"</script>

      ... everything else
   </head>

Then you can use CSS to hide/show based on if JavaScript is enabled/disabled:

/* Hide by default, show if JS is enabled */
#needsJS     { display: none  }
.js #needsJS { display: block }

/* Show by default, hide if JS is enabled */
.js #fallback { display: none }

Solution 3:

It can't do it directly, and workarounds for it are usually awkward and wasteful.

Use progressive enhancement technique instead.


Solution 4:

Just make the website working without JS. If everything is fine, you can attach JS functionality with e.g. jQuery.

This is also called unobtrusive JavaScript.

So you basically don't distinguish between client with JS and client without JS. You don't provide different output. You set up your HTML code in such a way that you can easily identify the elements that should JS functionality an this functionality in a programmatic way.

This way is even easier for you as you don't have to think about different outputs and it guarantees that the site is also working without JS.


Post a Comment for "Can Php Detect If Javascript Is On Or Not?"