0

I am new to programming and I am out of my depth right now...

I am attempting to make an app that uses information based on the clicks of a button and can then give data analysis based on these button clicks. This works in pure Javascript, but I need to be able to save this data in a database so that I can log in at another time and pick up where I left off, not start all over again.

I need to be able to pass information stored in variables to the server to be saved in a database on one click of a button and also send information back to the javascript from the database on clicking a different button.

So far I have made a Flask app but I am struggling to connect the python controller with the javascript using AJAX.

There are a lot of questions on here already about this topic, but having read and tried all the solutions I can find, I am still struggling.

This is one solution I have found on here (Send POST data using XMLHttpRequest) but it is giving me a 400 error:

var xhr = new XMLHttpRequest();
            xhr.open('POST', '/postmethod', true); // '/postmethod' is where I am hoping to deal with this data on the python controller
            xhr.onload = function () {
                console.log(this.responseText);
            };
            xhr.send(data); //data is a map which contains about 20 key value pairs.

I expect that this would log the data onto the console, but it is not doing that. I may be completely wrong about the purpose of "console.log(this.responseText);".

This is as far as I can get with the python side of things:

@app.route('/postmethod', methods = ['POST'])
def postmethod():
    if request.method == "POST":
        //I want to execute database commands here using the data passed from the javascript. But I do not know how to get the data as a variable in Python from Javascript.

I would really appreciate an example of how to POST data using a button. I need to see code examples for both the python controller and the javascript.

I have found it very difficult to understand how the explanations I have read elsewhere work as it is assumed the syntax is understood, I would be so grateful if the syntax was obviously spelled out to me.

1 Answers1

0

the second parameter of xhr.open is the URL. I think you need to define the complete URL your backend is accessible on. e.g.

new XMLHttpRequest();
            xhr.open('POST', 'http://localhost:8080/postmethod', true); // '/postmethod' is where I am hoping to deal with this data on the python controller
            xhr.onload = function () {
                console.log(this.responseText);
            };
            xhr.send(data); 

orotype
  • 340
  • 3
  • 6
  • Thanks for your suggestion. I tried now with the full URL, but I still get the same 400 error message on the console: "POST /postmethod HTTP/1.0" 400. – DCamilleri Apr 09 '21 at 10:37