How to configure the GTAG User Id in external JS file by picking PHP variable?

Asked

Viewed 181 times

3

As PHP use in the backend, to configure the inline user id just give a echo of the variable $userId, for ex:

   if (isset($userId)) {
        $gacode = "ga('create', 'xxx', 'auto', {'userId': $userId});";
        echo sprintf($gacode, $userId);
        }     
   else {
        $gacode = "ga('create', 'xxx', 'auto');";
        echo sprintf($gacode);
        }

But how I want to use the tracking code in a file .js external (called at the bottom of the page’s HTML .php), instead of using inline, that doesn’t work.

The tracking code is basically this:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XXXXXXX', { 'user_id': 'USER_ID' });

This code is in the file I created gtag_user.js, I placed below the tagmanager lib (at the end of the page where the variable $userId is declared).

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXX"></script>
<script src="https://www.site.com/view/js/gtag_user.js"></script>

Where USER_ID must be equal to the variable $userId PHP. I made a few attempts with ajax but it didn’t work either. Is it possible? How?

  • 2

    For me to situate myself? Where is marked with <script> is PHP? The code that is not marked is JS? If so it would not be the case to change this seat marking?

  • 1

    @Augusto Vasques Yes, I checked.. already removed. Thanks for telling. This php is in the middle of the JS, to write the js as the user is logged in or not.

1 answer

2

As the file containing the HTML is .php you can do this:

<script>const USER_ID = '<?php echo $userId; ?>';</script> <!-- aqui é declarada a constante -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXX"></script>
<script src="https://www.site.com/view/js/gtag_user.js"></script>

In the script you need to change and put the constant in the object:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XXXXXXX', { 'user_id': USER_ID }); // retirei as aspas

This way you can use anywhere you need it. Example:

<script>

    if(USER_ID == ''){
        // usuario não está logado
    } else {
        // verifica o usuário
    }

</script>

Another way is to generate the script with php:

// user id
$userId = 12345;
// arquivo JS
$arquivo = file_get_contents("https://www.site.com/view/js/gtag_user.js");
// substitui tudo o que tier USER_ID pelo valor $userId
$script = str_replace("USER_ID", $userId, $arquivo);
// mostra o resultado
echo "<script>$script</script>";

Using cookies

In the comments the OP revealed another way to work using cookies. To illustrate, I created the following example:

php generates the cookie:

    if (isset($userId)) {
        setcookie("USER_ID", $userId, time()+3600, "/");
    }   

And the value is recovered by javascript:

    const getUserId = () => {
        let val = null;
        decodeURIComponent(document.cookie).split(";").forEach(item => {
            let i = item.split("=");
            if(i[0] === 'USER_ID'){
                val = i[1].trim();
            }
        });
        return val;
    } 

    const USER_ID = getUserId(); // recupera o valor

With that, the constant USER_ID can be used in other scripts.

  • Andrei, but in case I don’t want to use anything inline (a const inside the <script> tag). Anyway it is a good solution if you can use inline. + 1

  • 1

    @gustavox got it.... There’s another way. I’ll put it to you.

  • @gustavox before I create, let me explain to you more or less how it would work... I would get the whole content js and replace everything you have USER_ID for the value you want to use. What do you think?

  • I don’t know if I understand... js is static right, it can’t be rewriting js themselves because it would break to other users...

  • @gustavox it will not be rewritten in the file. The file will serve as template/base. Got it?

  • I think I got it, it should work then.

  • @Gustavox I’m going out, and then I put

  • Quiet, thanks for the force. abs

  • @gustavox there is another way to generate the script

  • So, unfortunately it didn’t work. as I said in the chat, I can not have anything inline. I think only using cookie or even ajax. I’m trying here, but I reopened the question and offered a reward.

  • 1

    @gustavox tranquil man! =)

  • 1

    Andrei, I was able to solve it using cookies through this article: https://www.analyticsmania.com/post/google-analytics-user-id-with-google-tag-manager/#Gref There are several other ways, but you have to configure in tagmanager.com, change the tracking code... So I wanted to suggest that you include in your response this reference, just to be more complete so I can mark as solved...

  • 1

    @gustavox I will read tomorrow calmly about the link you sent. But thanks for the feedback.

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.