arcanelogic
arcanelogic

Reputation: 13

How to send and receive data from server: python / flask / ajax/json GET POST requests

This may be a simple thing to do but I cannot figure it out for some reason. On the SAME webpage, I'd like to send the clicked word in HTML to the server, and have the server send it back and alert the word.

On the flask .py file, I have this (it used to look different and more reasonable but now idk what I'm even doing):

 @app.route('/render/', methods=['GET'])
 def render():

 if request.method == "GET":
    jsondata = request.get_json()
    query_string = request.query_string
    #data = json.loads(jsondata)
    print(query_string)
    if query_string != None:
        print(query_string)
    return render_template('read.html', yup=jsondata)

On the JavaScript/HTML side, the client sends the hovered-on word (and I know that the server sees it as, for example, "GET /render/?%22whats%22 HTTP/1.1" 400 -, but it's not quite retrieving it or sending it back.

$("#readMain").delegate("span", "mouseenter", function() {

var toSend = $(this).text();

$.ajax({
    url: window.location.href,
    type: 'GET',
    data: JSON.stringify(toSend),
    contentType: 'application/json; charset=UTF-8',
});

$("#readMain").delegate("span", "click", function() {
    var jsonStr = JSON.stringify('{{yup}}');
    alert(jsonStr);});

What to do? Please help!

Upvotes: 1

Views: 1394

Answers (1)

stackdave
stackdave

Reputation: 7054

if you use GET on the client you must to use request.args on the server request.get_json on the server is when you use POST on the client

for GET method you must use something like that:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/")
def hello():
    all_args = request.args.lists()
    return jsonify(all_args)

for POST method; something like that:

if request.mimetype == 'application/json':
   res = request.get_json()
else:
   res = request.form

Upvotes: 1

Related Questions