1

I have some created some variables in Javascript to tracker how long an individual holds a button. I would like to pass these variables within a class in python (oTree) to store the data.

So, suppose the Javascript code is as follows:

let javascriptvariable = 0;

This javascriptvariable will be updated as the user clicks the button, so let's say the final value is javascriptvariable = 100. The python code is below.

class DisplayCharacteristics2(Page):
    form_model = 'player'
    pythonvariable = javascriptvariable


    @staticmethod
    def vars_for_template(player: Player):
        return {
            "var1": player.var1,
        }

I tried created an empty variable, but I get an error which says something like javascript can't "add" to a null variable. I also tried using django in combination with javascript (see below), but javascript cannot add to a null variable. I tried to let it equal to zero first, but then I only get data points of 0.

let javascriptvariable = `{{ pythonvariable|safe }}`

Any leads will be appreciated! Thanks in advance.

1 Answers1

1

Using live pages seems to solve the issue.

https://otree.readthedocs.io/en/latest/live.html

So in Javascript:

 function sendTracker1() {
          liveSend({'which_char': 'char_1', 'value': tracker1})
      }

And in Python:

class MyPage(Page):
    form_model = 'player'

    @staticmethod
    def live_method(player, data):
        if data['which_char'] == 'char_1':
            player.timer_char1 = int(data['value'])