Reputation: 1157
I'm trying to figure out how to use jQuery AJAX with Python's Bottle module.
Here is my initial attempt but it isn't working and I'm really hitting a wall (been programming all day and my brain is a bit fried):
from bottle import route, request, run, get
@route('/form')
def construct_form():
return '''
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
$.ajax({
type: 'POST',
url: '/ajax',
data: $(this).serialize(),
success: function(response) {
$('#ajaxP').html(response);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" action="/ajax">
<input id="ajaxTextbox" name="text" type"text" />
<input id="ajaxButton" type="button" value="Submit" />
</form>
<p id="ajaxP">Nothing to see here.</p>
</body>
</html>
'''
@route('/ajax', method='POST')
def ajaxtest():
theText = request.forms.text
if theText:
return theText
return "You didn't type anything."
run(host = 'localhost', port = '8080')
Basically, what I want to be able to do is enter text into the textbox, click the button, and have the innerHTML of "ajaxP" change to the entered text.
No errors, it just doesn't do anything when I push the button.
Any help?
Upvotes: 3
Views: 10882
Reputation: 26
Please modify the type of the form button to type= "submit"
and not "button"
.
Upvotes: 0
Reputation: 298582
$("#ajaxP").load("/ajax", ...
sends a GET
(not a POST
) request to /ajax
and replaces the content of #ajaxP
with the response HTML.
You can fix your problem by changing method='POST'
to method='GET'
in your Python code.
Or you can fix your JS by preventing the form submit and sending an AJAX request instead:
$(document).ready(function() {
$('form').submit(function(e) {
$.ajax({
type: 'POST',
url: '/ajax',
data: $(this).serialize(),
success: function(response) {
$('#ajaxP').html(response);
}
});
e.preventDefault();
});
});
Upvotes: 2