Home > Software engineering >  How can I get Text from Js to Python
How can I get Text from Js to Python

Time:04-15

<script>
    function voice(){
        var recognition = new webkitSpeechRecognition();
        recognition.lang = "en-GB";
        recognition.onresult = function(event){
            console.log(event);
            document.getElementById("speechto").value = event.results[0][0].transcript;
        }
        recognition.start();


    }

</script>

I am making language translator web-app. And in above code, it takes input from the user using mic and print that in textarea in eng language. So I want this text in my python so that I can translate it and print it on another textarea. But i dont know how can I get that text from the js into my python code. any soln?

CodePudding user response:

Where is "your python"? I'm assuming this is on a browser over a network. You gotta set up a webserver (in python) to listen to network responses. Try webpy for a simple solution: https://webpy.org/.

You'll have to set up a URL endpoint to respond to POST requests. More info here: https://webpy.org/docs/0.3/tutorial#getpost.

And lastly, you'll have to set up your Javascript to send the post request and to use the response from your server to edit the textarea. You can use the JS fetch API to send the post request and handle the response from there.

Good luck hooking everything up

CodePudding user response:

I assume you're using flask as that is tagged in your question. You need to establish a route to execute your python code and run your flask app which should listen to some TCP port on your computer (by default flask seems to use port 5000).

Then on your js code you can use the fetch method to send the text to that port. For example:

fetch('http://locahost:5000/{your flask route goes here}', {
    method: 'POST',
    headers: {
        'Content-Type': 'text/plain',
    },
    body: {text you want to send goes here},
})
  • Related