1

(I am a complete beginner when it comes to any back-end development so I apologise if any terms are used wrong)

I have some javascript controlling a canvas game and I have a prolog planner which can solve the game. I am now trying to connect the two and have set up a flask server which can successfully call prolog, get the correct plan and send it back to the javascript. I am really struggling with getting the right inputs from the javascript.

Javascript:

var state = {
  state : "[stone(s1),active(s1), stone(s2), in(app2,s2), unlocked(app2)]"
}

stone2.on('click',function(){
  $.ajax({
    type: 'POST',
    contentType: 'application/json',
    data: state,
    dataType: 'json',
    url:'http://localhost:5000/next_move',
    success:function(data, textStatus, jqXHR){
      console.log(data);
      alert(JSON.stringify(state)); //making sure I sent the right thing
    }
  });
});

Flask server

//variables I use in the query at the moment
state = "[stone(s1),active(s1), stone(s2), in(app2,s2), unlocked(app2)]"
goal = "[in(app1,s1),in(app1,s2)]"
@app.route('/next_move', methods=['POST'])
def get_next_step():
  own_state = request.json
  r = own_state['state']
  output = subprocess.check_output(['sicstus','-l','luger.pl','--goal','go('+state+','+goal+').']) 
  //I would like to use the string I got from my browser here
  stripped = output.split('\n')
  return jsonify({"plan": stripped})
  //the correct plan is returned

I have seen the other questions regarding this, in fact the attempt I posted is from flask request.json order, but I keep getting 400 (BAD REQUEST). I'm guessing flask changed since then? I know it sends the json correctly because if I don't try to touch it I get the success message in my browser, so it is purely my inability to access its fields or to find any examples.

Community
  • 1
  • 1
bamboo10
  • 133
  • 2
  • 14

1 Answers1

1

What you're sending through POST is not JSON. It's just a set of key value pairs and as such you should just send it through as that. And get it out using request.form.

In your case I would also not use jQuery's $.ajax and use $.post instead.

Here is the code:

stone2.on('click',function(){
$.post('http://localhost:5000/next_move',
       state,
       function(data) {
         console.log(data);
         alert(JSON.stringify(state));
       }
);

@app.route('/next_move', methods=['POST'])
def get_next_step():
  own_state = request.form
  r = own_state['state']
  print r
  return jsonify({"plan": "something"})
mck
  • 2,040
  • 3
  • 19
  • 29