0

I have two similar JQuery ajax calls in my page that seems to behave differently:

$(".influence").click(function() {
    $(this).text(parseInt($(this).text()) + 1);
    var $state = $(this).parent();
    var faction = $("#faction").text();
    $.ajax({url: '/api/add_influence',
                data: {'state_id': parseInt($state.attr("stateid"))
                      ,'faction': faction
                    ,'game_id': $('#uid').text()},
                type: 'POST',
                success: function(response) {
                    $(this).text(response['new_infl']);
                },
                error: function(error) {
                    console.log(error);
                }
            })
    $state.render_state();
    return false;
    });

$("#submit").click(function() {
    var faction = $("#faction").text();
    $.ajax({url: '/api/submit_move',
                data: {'faction': faction
                    ,'game_id': $('#uid').text()},
                type: 'POST',
                success: function(response) {
                    $("#status").text(response["player_status"]);
                },
                error: function(error) {
                    console.log(error);
                }
            })
    return false;
    });

..and this is the Flask code in my app:

@app.route('/api/add_influence', methods=['POST'])
def apply_command():
    ...blah blah blah...
    return json.dumps({'new_infl': state.influence[faction]})


@app.route('/api/submit_move', methods=['POST'])
def submit_move():
    ...blah blah blah...
    return json.dumps({'player_status': 'Your turn'})

The first works, in particular response['new_infl'] is the value that I sended as a response.

The latter behave differently, if I log response["player_status"] it prints undefined, but if I log response it prints the correct JSON {"player_status": "Your turn"}

What am I missing here?

Hrabal
  • 2,403
  • 2
  • 20
  • 30
  • are you sure that response is treated as object and not as string? Have you tried to call jQuery.parseJSON() ? – Kostya Shkryob Aug 18 '16 at 13:07
  • Instead of using `$.ajax()` you should use `$.getJSON()`, that'll handle the JSON parsing and hand you a nice JSON object instead of a jqXHR object. – sethmlarson Aug 18 '16 at 13:15
  • 1
    [You should use `jsonify` instead of `json.dumps`](http://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify). – dirn Aug 18 '16 at 13:41
  • @dirn `jsonify` solved the problem, thanks, but my question remains, why the two different behaviors? – Hrabal Aug 18 '16 at 13:54
  • 2
    When you return the result of `json.dumps`, you are returning a string. Your response will have a content type of `text/html`. In order for JavaScript to implicitly handle it as JSON, it needs a return type of `application/json`. I'm not sure why it ever worked for you. – dirn Aug 18 '16 at 14:44

0 Answers0