Unable to retrieve nested objects when passed to Flask through an AJAX POST request

I'm currently facing an issue with POSTing an object to Flask using AJAX. Everything works fine when the object is simple, however, when it contains a nested object, Flask seems to receive the data in an unusual format.

Below is the AJAX POST snippet:


var req = "commit_url";
var data = {"longURL":"www.google.com",
        "product":"FIN",
        "project":"Zeus",
        "platform":"Twitter",
        "theme":["Tech"],
        "owner":"Tom"};
var submitData = {"req":req, "data":data};

console.log(submitData)

$.ajax({
  url: "http://xxx.xxx.xxx.xxx:5000/",
  data: submitData,
  type: 'POST',
  success: function(response) {
    var result = JSON.parse(response);
    printShortURL(result.shortURL);
  },
  error: function(error) {
    alert("Error contacting the server. See console for details.")
    console.log(error);
  }
});

Upon submitting the data, the console displays the following output:


{"req":"commit_url","data":{"longURL":"www.google.com","product":"FIN","project":"Zeus","platform":"Twitter","theme":"["#Tech"]","owner":"Tom"}}

Here's the python code in Flask:


@app.route("/", methods=['POST'])
def getData():
  f = request.form;
  print f
  req = f['req'];
  print req
  longURL = request.form['data[longURL]'];
  print longURL
  product = request.form['data']['product'];
  print product

  shortURL = '4Fi92v';

  return json.dumps({'status':'OK','shortURL':shortURL});

The response received by Flask looks like this:


ImmutableMultiDict([('data[longURL]', u'www.google.com'), ('data[project]', u'Zeus'), ('data[theme][]', u'#Tech'), ('data[owner]', u'Tom'), ('data[product]', u'FIN'), ('req', u'commit_url'), ('data[platform]', u'Twitter')])
commit_url
www.google.com
xxx.xxx.xxx.xxx - - [06/Feb/2018 12:21:08] "POST / HTTP/1.1" 400 -

Instead of preserving 'data' as an object key, Flask changes it to 'data[project]'. I can access the individual variables but prefer passing the entire 'data' object to another function directly without having to reference each variable separately.

I believe the issue lies within the JavaScript code, and despite attempts with JSON.parse and JSON.stringify, the problem persists.

Answer №1

When sending data as a json string, use the JSON.stringify method. In the backend, when receiving the data as an ImmutableMultiDict object, convert it to a dictionary using the to_dict() method.

var req = "commit_url";
var data = {"longURL":"www.google.com",
        "product":"FIN",
        "project":"Zeus",
        "platform":"Twitter",
        "theme":["Tech"],
        "owner":"Tom"};
var submitData = {"req":req, "data":data};

console.log(submitData)

$.ajax({
  url: "http://xxx.xxx.xxx.xxx:5000/",
  data: JSON.stringify(submitData),
  type: 'POST',
  success: function(response) {
    var result = JSON.parse(response);
    printShortURL(result.shortURL);
  },
  error: function(error) {
    alert("Error contacting the server. See console for details.")
    console.log(error);
  }
});

Then in your backend:

@app.route("/", methods=['POST'])
def getData():
  f = request.form.to_dict();
  print f
  req = f['req'];
  print req
  longURL = f['data'];
  print longURL
  print product

  shortURL = '4Fi92v';

  return json.dumps({'status':'OK','shortURL':shortURL});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Spacing and filtering strings in a React array

i am attempting to include space to the names filtered by the filter, but all the names are coming back without any space. How can I modify the filtered array to have space between each name? here is how it currently looks like - https://i.sstatic.net/AznK ...

Using jQuery, select a JavaScript array from an external file by pointing to it based on the option chosen in a dropdown menu

Currently, I am in the process of developing a page translation feature using jQuery. It functions flawlessly when all languages are contained in a single lang.js file within an array. Nonetheless, if the project expands significantly with numerous languag ...

The TypeScript declarations for the scss module are malfunctioning

Just recently, I set up a React project using rollup. Below is the configuration file for my rollup setup: rollup.config.js import serve from "rollup-plugin-serve"; import livereload from "rollup-plugin-livereload"; import babel from &q ...

Looking for assistance with jQuery navigation - struggling with positioning and accordion functionality

The sidebar navigation on this page: needs some attention. I have identified a few issues that need resolution and would appreciate some assistance: The accordion function is working correctly, but the single line item links (those that do not accord ...

Using jQuery, implement a functionality where a line break is added when the Enter key is pressed. Furthermore, the added

I have a text box where users can add cars to a list. Each car is entered on a new line, and when the user presses enter, jQuery adds a \n to move to the next line. However, when I collect this string, the \n characters are "hidden" and cannot b ...

Importance of body background color attribute

My CSS sets the body to a blue color, but my JavaScript changes the body color every second. It was working fine until I added a global CSS file. Unfortunately, I can't remove this CSS file because it contains many important rules that I need. I&apos ...

What changes can be made to the function below to ensure it reads up to 3 decimal

I am utilizing a javascript function called tafgeet to convert numbers into Arabic words. However, the issue is that it only supports up to 2 decimal places. How can I adjust the function to handle 3 decimal places? Currently, it translates numbers up to ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

.NET 6's JsonSerializer.DeserializeAsync is throwing a null value error when attempting to assign to a non-

I am encountering an issue with JsonSerializer while deserializing a post request from a client. The serialized class has non-null and required properties, but the Json serializer is setting them to null instead of throwing an exception. Current behavior: ...

Transform <td> tags into an array using Javascript

I am aiming to create an array and then add some data using the .unshift method. Is it possible to have an array that only contains td elements, created with JavaScript rather than jQuery? Below is a snippet of my table: <table id="scorestable"> ...

Split the JSON response into different arrays

I am attempting to split this JSON response into multiple arrays that I can utilize on the front end. The JSON response looks like this: { "clients": [ { "id": "2", "f_name": "test", "l_name": "test", "email": "<a href="/cdn-cgi/l/email-protec ...

Avoid loading the page when the browser's back button is pressed with vue-router

In my application, I have a "Home" page as well as a "Success" page. On the Success page, there is a button that, when clicked, redirects to a URL like https://google.com, using window.location.href='https://google.com'. Currently, I am able to ...

Is it possible to utilize CSS to form a triangle outline on the right-hand side of a Bootstrap list group?

https://i.sstatic.net/vSoa0.png Hey everyone! I'm trying to achieve a triangle shape using CSS at the end of a list item. I've utilized the list group component from Bootstrap to display my list. Below is a snippet of my code. I've als ...

Is it possible for Node.js to manipulate video files?

I'm curious about the compatibility of Node.js with videos, specifically in terms of editing rather than just playing them. My ultimate goal is to be able to reverse videos online. While Java seems like a solid option so far, I am drawn to Node.js for ...

"Encoding and Decoding Basic Custom Data Types in Elm: A Step-by-Step Guide

When working with Elm, I discovered that there isn't a built-in method for encoding/decoding custom types. This can present challenges when trying to send and receive custom-typed values to JavaScript. For example, how should we handle simple custom t ...

Tips for setting a select list to have no elements pre-selected when using the jQuery bsmSelect plugin

Looking for a way to have the jQuery bsmSelect plugin start with nothing selected by default? This handy plugin makes it easy for users to choose multiple options from a dropdown list, but you need it to begin blank. Any suggestions on how to achieve this? ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...

Why does serializing a JavaScript Object to JSON result in "{}"?

Hello fellow developers, I'm currently working on setting up a LocalStorage feature for my web application. One issue I've come across is that all objects in the Model abstraction layer need to be serialized. I understand that functions aren&a ...