Using AJAX, FLASK, and JavaScript to send an existing array to an endpoint

Having trouble POSTing the array songFiles generated by the getTableData() function (inside an ajax request) to the /api/fileNames endpoint, and then handling it in the postFileNames() callback function. Any assistance or alternative approaches would be greatly appreciated.

As a newcomer to ajax and flask, I've searched extensively for a solution but haven't found one that fits my specific needs. I apologize for my lack of expertise in this area.

JavaScript Code

function getTableData() {
    $.ajax({
        method: "GET",
        url: "/api/getSong",
        dataType: "json",
        success: function(data) {
            createMusicTable();
            
            let indexObj = Object.keys(data.song).length;
            
            for (var i = 0; i < indexObj; i++) {
                var song = data.song[i]
                var id = data.song[i].song_id;
                var fileName = data.song[i].song_file + ".mp3";
                
                songFiles.push(fileName);
                appendMusic(song, id);
                
                songTitle.id = "s" + i;
                console.log("td-ok");
            }
            postFileNames(songFiles);
        }
    });
}
function postFileNames(data) {
    $.ajax({
        method: "POST",
        url: "/api/fileNames",
        dataType: "json", // Unsure about this due to data being an array
        data: data, // Not certain if this is correct
        success: function(data) {
            console.log(data)  // Expected behavior: post data to the endpoint. Data is not logged and goes directly to error.
        },
        error: function() {
            console.log("cry")  // Logs an error message
        }
    })
}

FLASK Endpoint Code

@app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
    data = request.get_data() // Unsure about what to do here
    return data 
else:
    return "error" // Currently returns 'error'

Answer №1

@app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
    data = {
    "id": request.json["id"],
    "song_name": request.json["song_name"],
    "time_duration": request.json["time_duration"]
}
    return data, 200
else:
    return "error", 400 # currently goes to 'return error'

Would look even better if you did this:

@app.route("/songs/", methods=['GET', 'POST'])
def songs():
  return Songs().get_songs(), 200

In the routes.py file and keep the other classes and methods in a separate file

If mapping the array elements is an issue, consider using jsonify(array) or json.dump(array).

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

Intermediary Server Facilitating Video Negotiation in WebRTC Piping

In the process of developing a 3-part system for enabling remote vehicles to connect to a base station via WebRTC, my goal is to transmit video from the remote vehicle to a remote station using an RTC Peer Connection. The architecture of this system can be ...

While continuing to input text, make sure to highlight a specific element from the search results list

Currently, I am using a customized search feature in my React.js application. I am looking for a way to focus on an element within the search results so that I can navigate using arrow keys. At the same time, I need to keep the input field focused to conti ...

Adding fresh data to a JSON key in Python

I have a JSON string retrieved from my MySQL database that I need to update by adding another value to the daysOff property. After appending this new value to the JSON string, my goal is to then update the corresponding table in the database with the modif ...

Tips for aligning an element vertically when it has a float using CSS or JavaScript

I am struggling with centering the image within the article list loop I created. The code snippet looks like this: <article class="article <?php if($i%2==0) { echo 'even'; } else { echo 'odd'; } ?>"> <section class ...

What are the steps to keep a web application from closing on Android when the back button is pressed?

I am currently working on a HTML5 web application and packaging it with Cordova (phonegap) 1.7. My goal is to customize the behavior of the Android back button so that instead of closing the application by default, it navigates back using window.history.b ...

The array is displaying only the initial value upon comparison

Looking for a solution to compare values in an array received from a post request. Here's what I have tried: Example: if ($q->param('tradesFour[]') =~ m/Steel/) The array data is as follows: 'tradesFour[]' => [ 'S ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

No matter the method used for sending, the request body from post always returns as undefined

I have encountered a problem where none of the existing answers have helped me resolve it. I am attempting to pass a variable through ajax in the following manner: var myData = "Hi Og"; $.ajax({ type: 'POST', data: myData, url: &a ...

npm socket.io installation failed due to node version being less than 0.10.0

Having trouble installing socket.io on my BeagleBone Black because my system is using Node v0.8.22, but the required version for installation is above 0.10.0. Unfortunately, I am unable to upgrade my Node. /usr/bin/ntpdate -b -s -u pool.ntp.org cd /var/li ...

What is the best way to represent objects in a user interface?

Currently, I have some information stored in the following format: data : { full_name: 'John Doe', date_of_birth: '01-01-1990' } I am looking to display this data in a table-like format that resembles: Full Name: John Doe Date Of B ...

Having trouble choosing an option from the dropdown menu with Puppeteer Js

I need help with Puppeteer JS to select the initial element in a dropdown. Any suggestions? Once I input the city name in the text field, I want to choose the first option from the dropdown menu. const puppeteer = require('puppeteer'); (async ...

Determine the overall sum of rows present within this particular tbody section

I am struggling to calculate the total number of tr's within my nested tbody, but I am not getting the correct count. The jQuery code I used is returning a high number like 44 rows instead of the expected 7 rows. Can anyone point out where I might ha ...

Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS const http = require('http'); const fs = require('fs'); var options = { hostname: 'www.postcatcher.in', port: 80, path: '/catchers/5531b7faacde130300002495&apo ...

Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further d ...

What could be causing the input event not to be triggered consistently when I select or highlight text?

I have implemented a 4-digit pin field with a specific behavior: when a field is filled, the focus automatically shifts to the next field (the cursor moves to the next input field). If text in a field is deleted, the text in that field is also removed and ...

Angular 12: Running ng test shows code coverage error - TypeError: Unable to access 'initialize' property as undefined

I encountered an error in the code coverage console: TypeError: Cannot read properties of undefined (reading 'initialize') I am trying to call a service method from the component.ts file The code in the component.ts file looks like: this.myAuth ...

PhantomJS Alert: UnresolvedPromiseRejectionNotice

My main objective is to extract data from a website using Node.js. I have successfully managed to gather information using the request package, however, the website I am targeting contains dynamic content which cannot be accessed solely with request. Aft ...

Using a declared const in a separate React file

I've been searching for a solution, but haven't found anything that helps. I'm trying to retrieve data from an API and pass it to another page. The information is currently defined as "drink.strDrink", including the name and image. However ...

Iterating over an object in a React component

i'm trying to generate an object using iteration like this: opts = [{label:1, value:1}, {label:4, value:4}] the values for this object are coming from an array portArray = [1,4] I'm attempting to do const portArray = [1,4]; return { ...

Remove the preset text in an input field by clicking on it

Looking for help: <input name="Email" type="text" id="Email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f7fff3fbfed2f3f0f1bcf7eaf3ffe2fef7">[email protected]</a>& ...