Home > Blockchain >  AJAX/FLASK/JS: How to POST existing array into endpoint?
AJAX/FLASK/JS: How to POST existing array into endpoint?

Time:05-07

I am trying to POST the songFiles array pushed from the getTableData() function (inside the ajax request) into the /api/fileNames endpoint, which is then sent to a callback postFileNames() that should post the array, but I just can't seem to get it working. Any help would be appreciated, including maybe other ways to do this.

I'm a bit of beginner with using ajax and flask, I have scoured far and wide for a solution, but can't seem to find any to fit my goal, forgive my lack of knowledge.

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", // data is an array, so not sure what to put here. 
        data: data, // not sure if correct
        success: function(data) {
            // should: post the data into the endpoint.
            // data is not logged, goes straight to error.
            console.log(data)
        },
        error: function() {
            console.log("cry")
        }
    })
}

FLASK Endpoint Code

@app.route("/api/fileNames", methods=['POST', 'GET'])
def fileNameStorage():
if request.method == 'POST':
    data = request.get_data() # not too sure what to do here either.
    return data 
else:
    return "error" # currently goes to 'return error'

CodePudding user response:

@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 be more prettier if you would :

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

In routes.py file and the other classes and methods in another file

Maybe try jsonify(array) or json.dump(array) if it's a problem to map the array elements.

  • Related