Search code examples
javascriptphpjquerycakephp-3.x

How can I use a cake element in to jquery?


I'm using CakePHP 3, let me tell you what I'm trying to do, is to display the cake element in a div using a screen width condition, it throws the following error Uncaught SyntaxError: Unexpected identifier. From already I tell you that nothing happens with the syntax, no comma, period, etc. I'm missing.

What I need to know is the correct way to put the element helper inside jquery This one: <?= $ this->element('Search/Legislacion/form-search-legis') ?>

<script>
    $(document).ready(function(){
        var width = $(document).width(),
            search_form_legis = "<?= $this->element('Search/Legislacion/form-search-legis') ?>"; 

        // console.log(width);

        if(width >= 576){
            $('#searchDesktop').html(search_form_legis);
        }
    });
</script>

Solution

  • You can't just dump HTML into a JavaScript string, as soon as the first single/double quote occurs, it will break things as that will close the string, just look at the source of the page that is being delivered, there will be something like this:

    search_form_legis = "<form method="POST" action="/url">...";
    

    Obviously that's broken syntax.

    If you want to place data from PHP in JavaScript, then it is advised to use json_encode(), it will transform the data into the correct format.

    var search_form_legis = <?= json_encode(
        $this->element('Search/Legislacion/form-search-legis')
    ) ?>;
    

    A string, as in your case, will automatically be quoted and escaped, ie you don't even need to put quotes around it, it will looks something like this:

    var search_form_legis = "<form method=\"POST\" action=\"/url\">...";
    

    That being said, if there isn't an overly good reason to not output the content at all, then you might want to consider using CSS rules to hide/show it instead, something along the lines of:

    #searchDesktop {
        display: none;
    }
    
    @media (min-width: 576px) {
        #searchDesktop {
            display: block;
        }
    }