GLaw1300
GLaw1300

Reputation: 205

Send JSON data to Flask server using JQuery .load()

I am trying to use JQuery's .load() function to send data to my Flask server and, using that, render a <div> that is loaded into the calling element. My call looks something like this:

$("#element").load(
  "/get_data",
  {"info": info} // this is the problem
)

However, when I try to access this data in my Flask backend, the data is of form byte-string. (Accessing with request.get_data() yields a byte-string and request.get_json() yields None).

This did not surprise me, as the same behavior occurs when I use .ajax() requests. With Ajax, I simply use data: JSON.stringify({"info":info}) and that sends a string easily read by json.loads to the Flask backend just fine. What befuddles me is when I attempt the same data packaging with .load(), the request to the server is a GET instead of a POST.

Per .load()'s documentation, "The POST method is used if data is provided as an object; otherwise, GET is assumed." I don't understand why the data being a JSON string alters the behavior of .load() this way.

I'm keen to understand this behavior, but my question is how can I send data using JQuery's .load() to a Flask backend as a POST request in form JSON, or at least readable as a json (e.g. JSON string)?

Upvotes: 0

Views: 540

Answers (1)

GAEfan
GAEfan

Reputation: 11360

Your code should work. You have data as {"info": info}, which is an object that .load should send as a POST. Make sure you are getting a JSON mimetype object from the server. Also, make sure your Flask view accepts the POST method:

from flask import Flask, request, Response
import json

@app.route('/get_data', methods = ['GET', 'POST'])
def get_data():
    payload_dict = json.loads(request.data.decode('utf-8'))
    # or try payload_dict = request.json
    print(payload_dict["info"])
    return Response(json.dumps({"info_response": "hello"}), mimetype='application/json')

And make sure you have info defined in {"info": info}

Thought about using getJSON: https://api.jquery.com/jQuery.getJSON/ ?

Upvotes: 1

Related Questions