skip to Main Content

I am using Flask and have an Ajax call to a view which finds some data within a coordinates range and I just want to be able to return that data. It is successfully reaching the view, querying the database and returning data, but no response is received at JavaScript code.

The Ajax call is like this:

    $.ajax({
      type: "POST",
      dataType: "application/json",
      url: "/getsignswithin",
      data: dataToSubmit,
      success: function(data) {
        console.log(data);
      }
    });

The Flask route is like this:

@app.route("/getsignswithin", methods=['POST'])
def signs_within():
    data = request.get_json(force=True)

    signs = db.signs.find({
      'location': {
         '$geoWithin': {
            '$box': [
              [ data['extent'][0],data['extent'][1] ],
              [ data['extent'][2],data['extent'][3] ]
            ]
         }
      }
    })
    print(dumps(list(signs)))
    #return jsonify(success=True)
    return dumps(list(signs)), 200, {'ContentType':'application/json'}

The print(dumps(list(signs))) shows the data, but nothing is received in the success part of the Ajax. No errors are reported to the browser console or the Python console.

I have tried with return jsonify(success=True), just to see if it returns anything, but that doesn’t work either.

Console Output:

127.0.0.1 - - [07/Jul/2020 17:06:12] "POST /getsignswithin HTTP/1.1" 200 -
[<listdatahere>]
127.0.0.1 - - [07/Jul/2020 17:06:13] "POST /getsignswithin HTTP/1.1" 200 -

2

Answers


  1. Chosen as BEST ANSWER

    Changing the datatype to just "json", not "application/json" enables it to return the data. Thanks newbie99 for the advice on the error callback which enabled me to identify the issue. I will remember to do that in my future troubleshooting.

      $.ajax({
          type: "POST",
          dataType: "json",
          url: "/getsignswithin",
          data: dataToSubmit,
          success: function(data) {
            console.log(data);
          }
        });
    

  2. You need to return it like this:

    json.dumps({'data': list(signs)}), 200, {'ContentType':'application/json'} 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search