Home > database >  How to call pass javascript value as parameter to python function
How to call pass javascript value as parameter to python function

Time:11-15

I have a HTML input and onClick with a button, I get the value of text input and store in a varibale in Javascipt. Now how can I use this varibale as a paramter to a python function?

In JavaScript I have:

var text = document.getElementById("text").value;

and in Python I have:

someFunction(text):
   print(text) # text is what I want to be passed from javascript

I am using pyscript to run my python codes

CodePudding user response:

You can do a GET or a POST from your page to the python script. AJAX makes this quite easy for you - there is an existing answer to a similar question here on stack, have a look at:

Passing Javascript variable to Python

You might find it easier to parcel up the variable in a little json, which makes the GET/POST nice and simple, then import json in your python code and modify the function accordingly.

Also probably need to define an endpoint so the server knows to execute the python script

CodePudding user response:

You can submit the form to send values to a Python file or use API's with Ajax this article about difference between server-side and client-side.

And in regard to @JohnHanley comment you can use py-script to do that, take a look here

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>

<script>
    name = "Guido" //A JS variable

    // Define a JS Function
    function addTwoNumbers(x, y){
        return x   y;
    }
</script>

<py-script>
    # Import and use JS function and variable into Python
    from js import name, addTwoNumbers

    print(f"Hello {name}")
    print("Adding 1 and 2 in Javascript: "   str(addTwoNumbers(1, 2)))
</py-script>

  • Related