Calling Python from Javascript

I’m trying to get a custom component’s properties from within Javascript. I could push by calling a javascript function, but it would be cleaner if I can either access these properties directly or call a python function to return these. I need it at the creatio, of the component so I tried:

var linkElement = this;
  anvil.call(linkElement, "my_method", "World").then(function (r) {
    console.log("The function returned:", r);
  });

from your documentation, removing the click event though. Nothing happens. I assume I’m not connected to the right DOM component, how do I know/find/set the right component?

Hi Kris, do you have a clone link you can share of just the component you’re trying to create?
It’ll be easier then to give some input…

There are a couple of ways you could achieve this I think.
Are you putting the component inside a custom_html form?
This way you can edit the custom_html property and put the js functions inside the script tags…
then… do a self.call_js(‘my_js_function’, arg1, arg2, arg3)
You’d call this js function in the form.show event - this way you’ll be accessing the correct dom element.

I think that this is a very clean example of adding js to a component which might help. https://anvil.works/library/slider

Will check the example later.

A clone link:
https://anvil.works/build#clone:AEYND7A6PUB2QQ6J=DBJU7SPGAKVHPC4BCMLONPPK

I think this might be what you’re aiming for?
https://anvil.works/build#clone:UKW57WZ26RIA7NXQ=UQAIN5PM6ULQUYOE2NSRYMWZ

2 Likes

Solved! That did it. Excellent. Txs!

Hi sc549,

I clone the app Forum Clone of TestScript and found where the Javascript function is called but cannot see where the javascript is actually placed. Could you please help?

from ._anvil_designer import Form2Template
from anvil import *

class Form2(Form2Template):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    # Any code you write here will run when the form opens.
    
  def my_method(self):
    return self.myproperty

  def form_show(self, **event_args):
    """This method is called when the HTML panel is shown on the screen"""
    self.call_js('test_function')

Hello @Tony.Nguyen

For reference, to help others more easily read your code please format code by wrapping it in backticks with the word Python.

For example,

```python

print('this will be syntax highlighted')

```

if you go to design view and find custom html then click edit… it’s in there

Screen Shot 2020-04-25 at 17.06.57

@ campopianoa Thanks for your reminder, I remembered … instead of ‘’’

@ sc549, I found it, thanks

3 Likes