0

i'm running a webserver using Node.js. I have 3 files: index.html, client.js and temp-meter.py.

PROBLEM : When clicking on the html button, my data isn't returned because i can't see it in my browser console. So i just need to get the result of my phython script and send it back to the 'client.js' file! This does not work.

index.html

This file has a simple button with an 'onclick-event' that calls a getData() function.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python Project</title>
</head>

<body>

    <button class="btn" onclick="getData();">Get Data</button>

    <script src="https://code.jquery.com/jquery-3.5.1.js"
        integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous">    </script>
    <script src="./client.js"></script>
</body>

</html>

client.js

The function getData() makes an ajax GET request and executes the python script:

function getData() {
$.ajax({
    method: 'GET',
    url: 'temp-meter.py',
    dataType: 'json',

    success: function (data) {
        const res = JSON.parse(data);
        console.log(res);
    }
});
}

temp-meter.py

import random
import json

def getData():
    arr = []
    i = 0

    for i in range(10):
        n = random.randint(-10,35)
        arr.append(n)

    som = 0

    for item in arr:
        som += item

    avg = som / 10
    avg = json.dumps(avg) #encode the data with json

    return avg #this avg needs to be returned to JS

When i simply alert(data) after the ajax request (success), then it alerts me the whole python script... (I just want the avg result).

Anjimlio
  • 15
  • 6

0 Answers0