How to Use Mobile Detect PHP with JS?

1.1k views Asked by At

I have a script that for some reason isn't working on mobile devices. Because of this I want to show a message to mobile devices only.

I found a PHP script that will do this but I am new to PHP and do not know how to implement this correctly.

In a PHP Page I have the following code:

<?php
  require_once 'Mobile_Detect.php';
  $detect = new Mobile_Detect;
?>
<!DOCTYPE html>
<html>
 <head>
   <script type="text/javascript">
     $(function() {
       if ( $detect->isMobile() ) {
         $( "body" ).prepend( "<p>You are on a mobile device.</p>" );
       }    
      });
   </script>
 </head>
 <body>
  <!-- Page Content -->
 </body>
</html>

When I run the above code it throws a syntax error.

How do I get the jQuery code to run if the device is a mobile device?

1

There are 1 answers

0
charlietfl On BEST ANSWER

You are trying to use a php value in javascript without ever printing it to the page:

TRY

<?php if( $detect->isMobile() ) : ?>
<!-- only place script in page if it is mobile -->
<script type="text/javascript">
 $(function() {
     $( "body" ).prepend( "<p>You are on a mobile device.</p>" );
  });
</script>
<?php endif ?>