I am new to PHP and Pushing variables to the Datalayer and for marketing reasons I am trying to push this to the data layer, what I have done is below
I have a form where I grab the variables from the form and store them in PHP variables, I then JSON encoded them to appear in a JSON format and push them to the console to view them it:
$myObj = new stdClass();
$myObj -> name = $firstName;
$myObj -> surname = $lastName;
$myObj -> number = $Number;
$myObj -> LRP = $response;
$myJSON = json_encode($myObj);
echo '<script type="text/javascript">' .
'console.log(' . $myJSON . ');</script>';
}
I then echo the data in a JS script using quotations which output it to the console for me in this format
"name": "John",
"surname": "Doe",
"number": "1234567890",
"LRP": "Success ID = 1"
I have tried the same method as above to then push this to the DataLayer but it keeps giving me the unexpected token error because the format isn't correct but I am unsure of what is wrong, my code is below:
echo '<script type="text/javascript">' .
'var datalayer = window.datalayer || [];
dataLayer.push({
(' . $myJSON . ')
});
</script>';
Is there any other form of documentation I can look at on how to push a PHP variable to the Datalayer or a fix inside my code?