Reputation: 495
I'm trying to receive a POST request containing user-input form data using AJAX, but I keep returning errors. I'm following this tutorial almost verbatim.
Here's my code:
views.py
@app.route('/table_data', methods=['POST'])
def table_data():
user_id = request.form['userID']
name = request.form['name']
return user_id, name #of course I'll return something more meaningful in the future
datapage.html
<script type="text/javascript" src="app/static/js/submit.js"></script>
<form action="{{ url_for('table_data') }}" class="form-inline" method="post"
role="form" enctype="application/json">
<input type="text" class="form-control" id="userID" placeholder="4-Character ID">
<input type="text" class="form-control" id="name" placeholder="Name">
<button type='submit' class="btn btn-default">Submit</button>
</form>
submit.js
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
userID: $('#userID').val(),
name: $('#name').val()
},
type: 'POST',
url: '/table_data'
})
event.preventDefault();
});
});
My console is returning "GET /app/static/js/submit.js HTTP/1.1" 404", even though I know that the route to submit.js is correct.
I'm brand new to JavaScript/jQuery. Any help for a rookie?
Upvotes: 2
Views: 6505
Reputation: 4489
Moved solution from question to answer:
SOLUTION:
First, thanks to @reptilicus for the solution to the 404 error on the .js file (see comments). After that I was stuck with a "Bad Request" error message (400) in the browser window because my HTML input parameters did not include "name". I added name="userID" and name="name" to the tags in the HTML script, and it ran.
Upvotes: 1