0

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?

KiriqN
  • 21
  • 4
  • 1
    The `(` and `)` parenthesis are not valid in [JSON](https://www.json.org/json-en.html). – KIKO Software Feb 04 '22 at 10:00
  • 1
    You should also remove the `{}` you add before and after in your `.push()`, since it will also give you invalid json: `.push({ {"name": ...} })`. If you mean to push a single object, just do `.push(' . $myJSON . ')`. If you meant to push it as an array containing that object, then just put the object in an array when encoding it: `json_encode([$myObj])` – M. Eriksson Feb 04 '22 at 10:04
  • Ok thank you for the input, I will look at this – KiriqN Feb 04 '22 at 10:08
  • Thanks @ M. Eriksson you were correct, the {} weren't needed and it's now displaying the data correctly in the data layer – KiriqN Feb 05 '22 at 11:15

0 Answers0