-1

I'm trying to get the lines of code below to help me write "<?php include('like.php'); ?>" on a page only when the visitor isn't using a a mobile device but it doesn't seem to be working. Any Ideas on how to get it to work.

<script type="text/javascript">
<!--
if (screen.width > 699 {
document.write("<?php include('like.php'); ?>")
}
//-->
</script>
Dz.slick
  • 413
  • 1
  • 4
  • 19

4 Answers4

3

By the time JavaScript is writing to the document, it's too late - PHP has already sent everything to the browser. Your next best approach would be to make an AJAX call to fetch the content and append it to the DOM.

Assuming you're willing to use a JavaScript framework like jQuery, it's quite simple:

if (screen.width > 699) {
    $.ajax({
        url      : '/like.php',
        dataType : 'html',
        success  : function(data) {
            $('#myContainer').html(data);
        }
    });
}

http://api.jquery.com/jQuery.ajax/

AlienWebguy
  • 73,720
  • 16
  • 109
  • 137
1

As others have mentioned, you can not have JavaScript include a piece of PHP-code and have it executed. As PHP is run server-side, before the page is served to the client, injecting the code like you suggest would just write <?php include('like.php'); ?> as plain text to the document.

You could however load the content of like.php through Ajax and inject it into the DOM, if a certain criteria is met.

With a library like jQuery, it is quite easy, as it provide a method .load() that let you load content into the DOM like that. You could do it something like this:

// Wait for the DOM to be ready
$(function () {
    // Check the width of the screen
    if (screen.width > 699) {
        // Load the content and add the HTML to an element
        $('#id-of-element-to-add-content-to').load('like.php');
    }
});

In the above example, the content of like.php will be loaded into the HTML-element with id id-of-element-to-add-content-to, but you could use any selector you like, that match your need. If you want to replace the entire body of the page, your could do $('body').load('like.php'); instead.

More about the available jQuery selectors: http://api.jquery.com/category/selectors/

Christofer Eliasson
  • 29,772
  • 6
  • 69
  • 99
0

javascript executes on the browser and php executes on the server so, you need to add an if condition and then include

shyam
  • 8,153
  • 4
  • 23
  • 40
0

you could test the user agent server side and append that line if not from a mobile device