Home > Software design >  Ajax post multiple data to flask
Ajax post multiple data to flask

Time:03-14

The way I send one data to flask

.js

function func(s) {

  let toPost = {name: f.name, sf: split.f};
  let jsonStr = JSON.stringify(toPost);
  $.ajax({
      url: "temp",
      type: "POST",
      data: JSON.stringify(data),
      processData: false,
      contentType: "application/json; charset=UTF-8",
      success: function(){
        console.log("success")
      }    
    });
}

.py

@app.route('/temp', methods = ['POST'])
def temp() :

    jsonStr = request.get_json()
    file_object = open('temp.txt', 'a')
    file_object.write(jsonStr)
    file_object.write("\n")
    file_object.close()

    return render_template('temp.txt')

But I would like to send multiple data, so the ajax look like this:

data: {str: JSON.stringify(data), method: "add"}

Everything else remains the same.

In the .py file how could I get both str and method as well?

errors

console

jquery-3.2.1.min.js:4          POST FILENAME 400 (BAD REQUEST)

com

127.0.0.1 - - [] "POST /FILENAME HTTP/1.1" 400 -

full error

enter image description here enter image description here

CodePudding user response:

Your code leaves a lot of room for speculation.
The error message you get results from the fact that you want to send data as JSON but do not format it completely compliantly.

Normally, submitted objects are automatically sent as form data and formatted accordingly beforehand. You suppress this behavior by setting the processData parameter to false. However, this also means that the formatting to JSON must also be done by you. Otherwise a string representation of the transferred object would be sent, which the server cannot interpret.

As the following example shows, you should convert all data to JSON using JSON.stringify(...) before sending it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
    <style media="screen">
      output {
        white-space: pre;
      }
    </style>
  </head>
  <body>
    <form name="my-form">
      <input type="text" name="name" />
      <input type="text" name="sf" />
      <input type="submit" />
    </form>
    <output name="result"></output>

    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>

    <script type="text/javascript">
      $(document).ready(() => {
        $('form[name="my-form"]').submit(function(evt) {
          evt.preventDefault();
          const form = $(this);

          const formData = {};
          $.each(form.serializeArray(), (_, row) => {
            formData[row.name] = row.value;
          });
          // => { name: <anything>, sf: <something> }
          console.log(formData);

          const method = 'add';
          const data = { data: formData, method: method };
          // => { data: { name: <anything>, sf: <something> }, method: "add" }
          console.log(data);

          $.ajax({
            url: '/temp',
            type: 'post',
            data: JSON.stringify(data),
            contentType: 'application/json; charset=utf-8',
            processData: false
          }).done(data => {
            $('output[name="result"]').html(data);
          });
        });
      });
    </script>
  </body>
</html>

Depending on the requirements, you can query the data on the server side using its key, since it has already been parsed from the JSON format.
Since you get a dict for your nested object because of this, a conversion to a string is necessary before you can write it to the file.

import json, os
from flask import (
    Flask, 
    render_template,
    request
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/temp', methods=['POST'])
def temp():
    data = request.json.get('data')
    method = request.json.get('method', 'add')
    if method == 'add' and data:
        path = os.path.join(app.static_folder, 'temp.txt')
        with open(path, 'a') as fp:
            print(json.dumps(data), file=fp)
    return app.send_static_file('temp.txt')

Please note that this is a simplified example trying to be based on your specifications.

  • Related