I am trying to send data from a javascript file to my python file. I am using flask to do so but I can't get the value from my JS file to my html template to pass it my python file. The values that are in my JS file are obtained through an EEG device which gives brain readings.
EDIT- I have tried to the browserify library but it did not make a difference. I also tried using require.js
main.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="../cortex/cortex-example-master/nodejs/src/raw.js"></script>
<script>
window.onload = function() {
// setup the button click
document.getElementById("theButton").onclick = function() {
doWork()
};
}
function doWork() {
// ajax the JSON to the server
$.post("receiver", JSON.stringify(dataArray), function(){
});
// stop link reloading the page
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<a href="" id="theButton">Click Me</a>
</html>
raw.js
const Cortex = require("../lib/cortex");
function raw(client, onResult) {
return client
.createSession({ status: "active" })
.then(() => client.subscribe({ streams: ["eeg"] }))
.then(subs => {
if (!subs[0].eeg) throw new Error("failed to subscribe");
const headers = subs[0].eeg.cols.slice();
headers.unshift("seq", "time");
headers.headers = true;
let n = 0;
const onEeg = data => {
if (n === 0) onResult(headers);
onResult([n, data.time].concat(data.eeg));
n++;
};
client.on("eeg", onEeg);
return () =>
client
.inspectApi()
.then(() => client.unsubscribe({ streams: ["eeg"] }))
.then(() => client.updateSession({ status: "close" }))
.then(() => client.removeListener("eeg", onEeg));
});
}
if (require.main === module) {
process.on("unhandledRejection", err => {
throw err;
});
const readline = require("readline");
const stdin = process.stdin;
readline.emitKeypressEvents(stdin);
if (stdin.isTTY) stdin.setRawMode(true);
const verbose = process.env.LOG_LEVEL || 1;
const options = { verbose };
const client = new Cortex(options);
// these values need to fill to run example
const auth = {
username: "prashanb",
password: "Basti123",
client_id: "BP9CKBpyiA0RbZqAXe7uEiDRju9m4N02e3KPWBlz",
client_secret: "n8ymWHCgndLBSYbIn2XShGLyb6WIc8I6dBMVRb84ZFsOciVjX3KZWsgFSgPCmbkxfmMRlVtmk6NmmjjvO7H8FYvCLH4Wt3nQ2hXi4QTsO4YjSneJra6jGpTwxgPha1dx",
debit: 1 // first time you run example debit should > 0
};
var eegData="hi";
var dataArray = ["mehani"];
dataArray.id="dataArrayId";
eegData.id="eegDataStuff";
client.ready
.then(() => client.init(auth))
.then(() => raw(client, rawData => dataArray.push(rawData.join(','))))
.then(finish => {
console.warn(
"Streaming raw data as CSV. Press any key to add a marker or escape to stop."
);
return new Promise(resolve => {
stdin.on("keypress", (char, key) => {
const time = new Date();
const { ctrl, alt, meta, name } = key;
if (!ctrl && !alt && !meta && name.match(/^[a-z0-9]$/)) {
client
.injectMarker({ label: "key", value: name, time })
.then(() => {
const ftime = `${time.toLocaleTimeString()}.${time.getMilliseconds()}`;
console.warn(`Added marker ${name} at time ${ftime}`);
});
} else if (name === "escape" || (ctrl && name === "c")) {
stdin.removeAllListeners("keypress");
stdin.pause();
resolve(finish());
}
});
});
})
.then(() => client.close())
.then(() => {
dataArray.forEach(function (item,index,array) {
console.log(item,index);
JSON.stringify(dataArray);
})
console.warn("Finished!");
});
// We could use the value returned by numbers) here, but when we ctrl+c it
// will clean up the connection anyway
}
module.exports = raw;
app.py
from requests import post
import data as data
from flask import Flask, render_template, request, redirect, Response
import json
app = Flask(__name__)
@app.route('/')
def output():
# serve index template
return render_template('main.html')
@app.route('/receiver', methods = ['POST'])
def worker():
data = request.get_json(force=True)
result = ''
# read json + reply
print(data)
return result
if __name__ == '__main__':
app.run()