0

My HTML file looks like this:

Sum: <div id="sum">?</div>

And the corresponding JavaScript like this:

 function refresh(){
     //Wait for request from Amazon Gateway API, then replace 'sum' with result of 
 Python function
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://8qp45dk604.execute-api.us-east- 1.amazonaws.com/beta", true);

xhttp.send();
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e){
    if(xhttp.readyState == 4 && xhttp.status == 200){

        var response = JSON.parse(xhttp.responseText);
        var a = response.a;
        var b = response.b;
        document.getElementById("sum").innerHTML = 
        resultOfPythonFunction('sum.py', 'sum', a, b);
    }
}
    setTimeout(refresh, 3000);
}

What should I replace the line resultOfPythonFunction('sum.py', 'sum', a, b); with in order to modify the div with the result of a Python sum function?

user5090779
  • 47
  • 1
  • 6
  • 1
    Possible duplicate of [Call Python function from Javascript code](https://stackoverflow.com/questions/13175510/call-python-function-from-javascript-code) – Luca Kiebel Sep 10 '18 at 15:52
  • You'd need to make another AJAX call to your server to run the python function. Which begs the question, why are you making an AJAX request to get something to feed to another AJAX request? Do all that on the backend. – Jared Smith Sep 10 '18 at 15:54

1 Answers1

0

The browser can't execute python code. To do what you're asking, you would have to set up a python back end that you could send HTTP POST requests to that would perform sum on your request body, and then send back the result. Some common tools for this are django, flask, and pyramid.

You could then grab this result and set it to the div in the way you did before.

izb
  • 562
  • 4
  • 11