DataGuy
DataGuy

Reputation: 1725

JSON to Python via AJAX

I have built a machine learning model that receives data via POST in Flask as follows:

@app.route('/api', methods=['POST'])
def make_predict(): 
    predict_request = [data["one"],data["two"],data["three"]] 
    predict_request = np.array(predict_request)
    #np array goes into random forest, prediction comes out
    y_hat = my_random_forest.predict(predict_request)
    #return our prediction
    output = [y_hat[0]]
    return jsonify(results=output)

if __name__ == '__main__':
    app.run(port = 9000, debug = True)

and Im trying to pass JSON to the model from a simple AJAX call and display the prediction result on the same page as follows:

<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script> 
  <meta charset="utf-8">
  <title>JSON Test</title>
</head>
<body>
  <button type="button" id="ok">Click Me!</button>
  <div id="name"><div>
</body>
</html>

here is the included script.js file:

<script>
$(document).ready(function(){  
$('#ok').click(function(){  
     $.ajax({  
         url:'http://127.0.0.1:9000/api',  
         type:'post',  
         dataType: 'Json',
data: {one:1.2,two:23.4,three:45.4},
         success: function(data) {  
             $('#name').val(data.output);     
         }
     });  
  });  
}); 
</script>

Two issues Im having:

  1. The script.js file is throwing an unexpected token > error. Its in the same folder as index.html so Im not sure why its giving the error.
  2. After I get passed the first error Im not sure if my ajax format is correct. can someone verify?

Thanks for all of your help on this.

Upvotes: 1

Views: 56

Answers (1)

Hassan Mehmood
Hassan Mehmood

Reputation: 1402

Hey try the following updated version of your AJAX request.

<script>
    $(document).ready(function(){  
    $('#ok').click(function(){  
         $.ajax({  
             url:'http://127.0.0.1:9000/api',  
             type:'post',  
             dataType: 'Json',
             data: JSON.stringify({one:1.2,two:23.4,three:45.4}),
             success: function(data) {  
                 $('#name').val(data.output);     
             }
         });  
      });  
    }); 
</script>

Upvotes: 1

Related Questions