Search code examples
javascriptdom-events

Javascript Document.write Issue


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>

Solution

  • 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/