Home > other >  Flask page receiving GET request instead of POST even if Ajax is sending POST
Flask page receiving GET request instead of POST even if Ajax is sending POST

Time:06-19

I don't know why, but I cannot receive POST method, instead I receive the GET method that I placed at the end of this post. I can't wrap my head around about what I am doing wrong. I suppose the interference must be with < form id="myForm" > Which should just call the function modify_event that would then send the POST request. So on the top of my head the solution would be replacing it and calling the function in another way, like the onclick for submit, but apparently it doesn't work?

Thanks everyone.

JS and HTML code :

<form id ="myForm" onsubmit="modify_event()">
      <!-- MODIFY EVENT MODAL -->
      <div >
        <div >
          <div >
              <div >
                <div >
                  <label for="startdate" >New date</label>
            <!-- HERE I PASS THE DATE -->      
                {{form1.startdate(class_='form-control')}}
                </div>

              <div >
                <button
                  type="button"
                  
                  data-bs-dismiss="modal"
                >
                Close
                </button>
                {{form1.submit()}}  
             </div>
           </div>
          </div>
        </div>
      </div>
    </form>

<script>
  function modify_event() {
    var value = document.getElementById('startdate').value;
    $.ajax({
              url: "/modify_appointment",
              type: "POST",
              data: {
                  new_date : value,
                  id: evId
              },
              success: function () {
                alert("Modified");
              }
          });
      }

Python backend code :

#Declaring the class 
class InfoForm(FlaskForm):
    startdate = DateTimeLocalField('Start date', format='%m-%d-%Y %h:%M', validators=[DataRequired()])
    submit = SubmitField('Submit')

#HERE IS WHERE I INITIALIZE THE FORM
@app.route('/')
def appointments():
    startdate = None
    form1 = InfoForm()
    cursor = mysql.connection.cursor()
    result = cursor.execute("select * from Appuntamento ORDER BY Data ASC")
    if result > 0:
        appuntamenti = cursor.fetchall()
        cursor.close()
        return render_template('appuntamenti.html', form1=form1, appuntamenti=appuntamenti)
    else:
        cursor.close()
        return render_template('appuntamenti.html', form1=form1)

#HERE IS WHERE THE POST SHOULD BE
@app.route("/modify_appointment",methods=["POST"])
def modify_appointment():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
        getid = request.form['id']
        new_date = request.form['new_date']
        new_date = parser.parse(new_date)
        cur.execute('UPDATE Appuntamento SET Data = {0} WHERE idAppuntamento = {1}'.format(new_date, getid))
        mysql.connection.commit()
        cur.close()
        msg = 'Record deleted successfully'
        return jsonify(msg)

What the form actually does:

GET /?startdate=2022-06-21T11:11&submit=Submit HTTP/1.1" 200 -

CodePudding user response:

Your form is submitted via GET because the form's default behavior is used and no method attribute is specified. Calling your JavaScript function on a submit event will be ignored.
To avoid this, you should pass the event object to the function and call preventDefault() which signals the browser to suppress the default action for this event. So you can send the form data with AJAX.

<form id="myForm" onsubmit="modify_event(event)">
    <!-- Your code here! -->
</form>

<script>
function modify_event(event) {
  event.preventDefault();
  /* Your code here! */
}
</script>

To reset the value of the input field, you can either assign a new value to the property value of the input field, or you reset the entire form. With the latter, the input field is assigned the value that was set after loading.

event.target.reset()

CodePudding user response:

I managed to "solve" by doing this although this solution is not optimal since the modal won't close automatically and it won't clear itself after sending the values.

{{ form1.submit(class_="btn btn-primary", onclick="modify_event()") }}
   

function modify_event() {
    var value = document.getElementById('startdate').value; 
    $.ajax({
        url: "/modify_appointment",
        type: "POST",
        data: {
            new_date : value,
            id: evId
        },
        success: function () {
            alert("Modified");
        }
    });
}
  • Related