phphtmljqueryajaxgoogle-trends

PHP error when trying to set html element to google trends embed


I am getting an error when trying to set the html property of an element with jquery to google trends embed.

<!DOCTYPE html>
<html>
<head>
    <title>Titlw</title>
</head>
<body>
    <div class="hide" id="google_trends"></div>
</body>
<script type="text/javascript">
    /*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */
</script>
</html>
<?php

echo "
<script>
    $('#google_trends').removeClass('hide');
    $('#google_trends').html('<script type=\"text/javascript\" src=\"https://ssl.gstatic.com/trends_nrtr/2213_RC01/embed_loader.js\"></script> <script type=\"text/javascript\"> trends.embed.renderExploreWidget(\"TIMESERIES\", {\"comparisonItem\":[{\"keyword\":\"a\",\"geo\":\"\",\"time\":\"today 5-y\"}],\"category\":0,\"property\":\"froogle\"}, {\"exploreQuery\":\"date=today%205-y&gprop=froogle&q='a'\",\"guestPath\":\"https://trends.google.com:443/trends/embed/\"});</script>');
</script>";


?>

Error message -

"Uncaught SyntaxError: Invalid or unexpected token"


Solution

    1. You do not need to print the output using echo function.It will embed itself within the specified div. Here the div id is google_trends
    2. Your requirement to show/hide google_trends div will be fulfilled by initializing jquery using ready function. Once the page loads, it will remove hide class and show google trend request results.
    3. Use renderExploreWidgetTo function than renderExploreWidget.With this, you can define your div id in which you want to display your output.

    Try the following code.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Titlw</title>
        
    </head>
    <body>
        <div class="hide" id="google_trends"></div>
    
    
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
        <script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1328_RC04/embed_loader.js"> </script>
     </body>
    </html>
    
    <script type="text/javascript">
    $( document ).ready(function() {
        $('#google_trends').removeClass('hide');
        trends.embed.renderExploreWidgetTo(google_trends,'TIMESERIES', {'comparisonItem':[{'keyword':'a','geo':'','time':'today 5-y'}],'category':0,'property':'froogle'}, {'exploreQuery':'date=today%205-y&gprop=froogle&q=a','guestPath':'https://trends.google.com:443/trends/embed/'});
    
    });
    
    </script>
    

    Note: This is a standalone code as I have added jquery CDN link and google trend's ember_loader js file.