'Pushing PHP variables to dataLayer using JS

I heard from a good friend that people in this community can be very helpful and good-hearted so I'd love some help from you peops!

I've been trying to push php variables to the datalayer using the .push() method in javascript (for google tag manager and google analytics). Below is the code snippet to better understand what's happening.

 <?php . . . . . . ?>
    
    <script language='javascript'>

     $(window).on("load", function() { 

     var variable1 = <?php echo $variable1_php; ?>;
     var variable2 = <?php echo $variable2_php; ?>;
     var variable3 = <?php echo $variable3_php; ?>;

      window.dataLayer.push({
             'event' : 'eventName',
             'variable1_for_gtm': $variable1,
             'variable2_for_gtm': $variable2,
              'variable3_for_gtm': $variable3,
});

});

</script>;
        
    <?php . . . . . .

What am I missing exactly? Thanks a lot!! P.S. Other events are correctly being tracked by GTM and recorded in GA.



Solution 1:[1]

Instead of using a $ sign just use variable names without it. $ sign is used for PHP variable names but not javascript.

 var variable1 = <?php echo $variable1_php; ?>;
 var variable2 = <?php echo $variable2_php; ?>;
 var variable3 = <?php echo $variable3_php; ?>;

window.dataLayer.push({
             'event' : 'eventName',
             'variable1_for_gtm': variable1,
             'variable2_for_gtm': variable2,
              'variable3_for_gtm': variable3,
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Tashfeen