2

My ajax call looks like this:

  $.ajax({
    url: "/doSomeCoolThingOnServer",
    type: "POST",
    async: false,
    data: {
      simple_string: "Variable sent from client side",
      array_of_strings: ["John", "George"],
      array_of_objects: [
        { city: "Shanghai", population: 1000 },
        { city: "Budapest", population: 2501 }
      ]
    },
    success: function(response) {
      console.log("===== SUCCESS =====");
      console.log(response);
    },
    error: function(response) {
      console.log("===== ERROR =====");
      console.log(response);
    }
  });

I am trying to receive the array of objects as an array of dicts on Python, but I am returned with an empty array.

@app.route("/doSomeCoolThingOnServer", methods=['POST'])
def doSomeCoolThingOnServer():
    simple_string = request.form['simple_string']
    array_of_strings = request.form.getlist('array_of_strings[]')
    array_of_objects = request.form.getlist('array_of_objects[]')

    print(simple_string) #returns desired string
    print(array_of_strings) # returns desired array
    print(array_of_objects) # returns empty array

Please advise how to receive array of objects as parameters in Python Flask passed as HTTP POST request using AJAX?

0

1 Answer 1

3

You could serialize your objects using JSON.stringify and deserialize then on the server with json.loads. This effectively sends your array of objects as array of strings.

Serialize for ajax call:

array_of_objects: [
    JSON.stringify({ city: "Shanghai", population: 1000 }),
    JSON.stringify({ city: "Budapest", population: 2501 })
]

Deserialize on server:

import json
array_of_objects = request.form.getlist('array_of_objects[]')
print([json.loads(s) for s in array_of_objects])

Another option is to serialize the entire array instead of every array element separately. This sends the array of objects as a single string:

array_of_objects: JSON.stringify([
    { city: "Shanghai", population: 1000 },
    { city: "Budapest", population: 2501 }
])

import json
array_of_objects = request.form['array_of_objects']
print(json.loads(array_of_objects))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.