How do I access a Wappler variable in JS?

I read everything on the forum, but it didn't help....

I define a variable like this:
dmx-value id="myvariable" dmx-bind:value="12"></dmx-value

Next, by pressing the button, I call a JS function that performs the following:

  console.log("dmx.global.data:", dmx.global.data);
  console.log("dmx.app.data:", dmx.app.data);
  console.log("dmx.app:", dmx.app);

all three objects exist and are output to the console,
next, I try to output the value of the variable, but none of the methods works - the answer is always undefined:

var Var1 = dmx.parse('myvariabe');
var Var2 = dmx.app.data.myvariable;
console.log(Var1);
console.log(Var2);

I've probably tried >10 variations already and haven't found the right answer yet. What is the right way?

Are you using content pages?
If yes, then must be something like:

dmx.parse('content.var1.value')

1 Like

I haven't seen such an option, but it didn't help either. I also tried content.myvariable.value and payment.myvariable.value. 'payment' is my content page name.

Why don't I see variables in the dmx.app.data object that are created by
"dmx-value id="myvariable" dmx-bind:value="12"></dmx-value"?

But if I create a variable in JS, it will be visible in dmx.app.data:
dmx.app.set('myVariable', 123123);

And in this case, JS has access to it....

Can you show the code? How are you calling the javascript? Under a function?

Try this:


function myfunction() {
var Var1 = dmx.parse('content.myvariabe.value');
console.log(Var1);
}

Then go to dev tools -> console and enter myfunction()
Check the output

2 Likes
<!-- Wappler include head-page="layouts/main" bootstrap5="local" is="dmx-app" id="testp" appConnect="local" fontawesome_5="local" -->
<dmx-value id="myvariable" dmx-bind:value="12"></dmx-value>
<meta name="ac:route" content="/testp">

<script>
    function getvar(){
        var Var1 = dmx.parse('content.myvariable.value');
        var Var2 = dmx.app.data.content.myvariable.value;
        console.log('VAR1=', Var1);
        console.log('VAR2=', Var2)
    }
</script>

<div class="container">
    <div class="row">
        <div class="col">
            <button id="btn1" class="btn" dmx-on:click="run({runJS:{name:'getmyvar',outputType:'text',function:'getvar'}})">Run JS</button>
        </div>
    </div>
</div>

it is working! Thank you very much!!!!!

1 Like

The second option is
var Var2 = dmx.app.data.content.myvariable.value;

it is working too

1 Like

Glad you got it working!

A friendly reminder that timing is a crutial thing here, you need to "wait" to AppConnect set myvariable and that's why the function() thing needs to be there.
Otherwise, the javascript will "read" something that doesn't exist (yet).
Should thanks also @famousmag who kindly remind me that on private while we were speaking :slight_smile:

2 Likes