My python severside code is not triggering when submitting from HTML form

Question:
My python severside code is not triggering when submitting from HTML form
Repl link:

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/generate-plan', methods=['POST'])
def generate_plan():
    print(f'we are inside server.py')
    if request.method == 'POST':
        topic = request.form.get('topic')
        duration = request.form.get('duration')
        vocabulary = request.form.get('vocabulary')
        materials = request.form.get('materials')
        print(f'Topic: {topic}')
        print(f'Duration: {duration}')
        print(f'Vocabulary: {vocabulary}')
        print(f'Materials: {materials}')

        # Generate the lesson plan
        lesson_plan = f'Topic: {topic}\nDuration: {duration}\nVocabulary: {vocabulary}\nMaterials: {materials}'

        # Return the generated lesson plan as a JSON response
        return jsonify({'lesson_plan': lesson_plan})

if __name__ == '__main__':
    app.run()

Change to app.run('0.0.0.0', 81)

This line is actually useless because if it’s not a POST method then it wouldn’t work anyway.

2 Likes

How are you submitting the form? Are you using this?

<form action="/generate-plan">

If so, you might need to change it to this

<form action="/generate-plan" method="POST">

You should also send the data using fetch requests instead using JS

<form>
  <input id="input1">
  <button onclick="submitForm()">Submit</button>
</form>
function submitForm() {
  fetch("/generate-plan", {
    method: "POST",
    body: JSON.stringify({"data": document.getElementById("input1").value})
  })
}

What this does is fire off an event that grabs the value of the input elements when the button is clicked, it then sends it using the more modern fetch requests. However when receiving this data in Flask, you need to call it using json.loads(request.data.decode('utf-8'))

2 Likes

if OP wants to use Python, let OP use Python
:face_with_diagonal_mouth:

1 Like

Server end is still python, just sending requests from client to server using JS instead of using the native action call