Reputation: 916
I'm trying to do a very simple example of form submission using ajax (POST) handled by a Python function using Tornado.
While it is working, so I can return a response, my main goal is to return some data without reload a new/same page. Only pass back some data, which should be handled by jQuery.
Here is my Python code:
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/(happiness)", Happiness),
]
settings = {
"template_path": Settings.TEMPLATE_PATH,
"static_path": Settings.STATIC_PATH,
}
tornado.web.Application.__init__(self, handlers, **settings)
class Happiness(tornado.web.RequestHandler):
def get(self, call):
resp = valid_calls[call]
if resp:
template, ctx = resp()
self.render(template, ctx=ctx)
def post(self, source):
text = self.get_argument('message')
self.write(text)
And here is my jQuery piece of code:
$(function() {
var text = ''
$('.error').hide();
$(".add_post").click(function() {
text = $("input#message").val();
if (text == "") {
$("label#name_error").show();
$("input#text").focus();
return false;
}
$.ajax({
type: "POST",
data: "message=" + text,
success: function(data) {
$('#left-menu').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>").append("<p>We will be in touch soon.</p>").hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='../images/arrow-up.gif' />");
});
}
});
});
return false;
});
So, my problem is not return something but return something without the need to load/reload the page.
Thank you for your help.
Upvotes: 1
Views: 6830
Reputation: 5804
Also ages late but here's another simple example that should cover browsers both old and new:
HTML
<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari/Chrome
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
</head>
<body>
<form name="f1">
<p>Input: <input name="word" type="text">
<input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/")'></p>
<div id="result"></div> <!--NOTE div id HERE-->
</form>
</body>
</html>
Python3
import tornado.ioloop
import tornado.web
import tornado.options
from tornado.web import Application, url
class AjaxHandler(tornado.web.RequestHandler):
def get(self):
self.render('ajax.html')
def post(self):
word = self.get_argument('w')
print('SUBMITTED: ', word)
msg = '<p>Output: ' + word + '<p>'
print('RETURNED: ', msg)
self.write(msg)
if __name__ == "__main__":
app = Application([
url(r"/", AjaxHandler)],
debug=True)
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Hope this helps!
Upvotes: 0
Reputation: 690
Ages late, but an example culled from various others
#!/usr/bin/env python
"""Basic tornado ajax example"""
from __future__ import print_function
from __future__ import unicode_literals
import os.path
import json
import tornado.auth
import tornado.escape
import tornado.ioloop
from tornado.options import define, options
import tornado.web
PORT = 6098
define("port", default=PORT, help="run on the given port", type=int)
class AjaxHandler(tornado.web.RequestHandler):
"""Simple, ajax handler"""
def get(self, *args, **kwargs):
"""get unlikely to be used for ajax"""
self.write("Not allowed")
self.finish()
def post(self, *args):
"""Example handle ajax post"""
dic = tornado.escape.json_decode(self.request.body)
print(dic)
# useful code goes here
self.write(json.dumps({'status': 'ok', 'sent': dic}))
self.finish()
class MainHandler(tornado.web.RequestHandler):
"""Simple example Main Handler"""
def get(self):
"""main page set up"""
self.render("tornado_index.html", messages=None)
class Application(tornado.web.Application):
"""Simple example App"""
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/(ajax)$", AjaxHandler),
]
settings = dict(
debug=True,
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "tornado_static")
)
tornado.web.Application.__init__(self, handlers, **settings)
def main():
"""start server"""
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
print(PORT)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
Hello <div id="togo" contenteditable>World</div>
<div>Change the word "World" and look at console </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function ajax_err(request, error) {
console.log(request);
console.log(error);
}
function ajax_ok(data) {
console.log(data);
}
function togo_blur() {
let r = {
url : '/ajax',
type : 'POST',
data : JSON.stringify({new_val : $(this).text()}),
dataType: 'json',
success : ajax_ok,
error: ajax_err
}
$.ajax(r);
}
$(document).ready(function() {
$("#togo").on("blur", togo_blur);
});
</script>
</body>
</html>
Upvotes: 2
Reputation: 494
check out this, it may help you. https://github.com/zhanglongqi/TornadoAJAXSample
Upvotes: 5