How do I handle AJAX requests?

3,739 views
Skip to first unread message

john2x

unread,
Mar 12, 2012, 8:40:55 AM3/12/12
to Tornado Web Server
I can't find it in the docs.

How do I check if the request is AJAX?

What do I return from the handler?

Thanks in advance.

Tate Kim

unread,
Mar 12, 2012, 12:13:35 PM3/12/12
to python-...@googlegroups.com
Hi,

I think the clue can be found by 'X-Requested-With' in request header.

In tornado, maybe you can get this by

self.request.headers.get('X-Requested-With')

Please let me know if there is a better way.



Regards,

Tate

Christopher Allick

unread,
Mar 12, 2012, 12:15:58 PM3/12/12
to python-...@googlegroups.com
Handling an ajax request in Tornado is pretty straight forward. There might be more complicated options, but here is how I do it:

I try and create general javascript functions for submitting to my server. And then create functions for creating the JSON objects I pass.

I create an object in javascript, put values in it, then send it via ajax to my tornado server

if test it a bit(could be more diligent) then i just turn it into a regular dict object in python. i do some stuff, then send back a json response saying "we're all good"

PYTHON TORNADO HANDLER:

class AddRoleHandler( tornado.web.RequestHandler ):
def post(self):
role = self.get_argument("role", None)
if role:
global ecs

role = json.loads( role );
result = ecs.add_role( role["name"], role["description"], role["keys"], role["uuid"] )
self.write(json.dumps({"msg":"role saved"}))

JAVASCRIPT:

submitRequest = function( req_obj, api_call, _callback ) {
if( typeof req_obj == "object" ) {
$.ajax({
type: "POST",
url: "/" + api_call,
data: {"role": JSON.stringify(req_obj)},
dataType: 'json',
success: _callback
});
}
}

roleAdded = function( data ) {
console.log( data );
window.location.reload( true );
}

addRole = function( ) {
var role = {}
role['name'] = $("#role_name").val();
role['description'] = $("#role_desc").val();
role['keys'] = [];
role['uuid'] = ecs.uuid();
$.each( $("#sending_keys input"), function(index,value) {
role['keys'].push( $(value).val() );
});

submitRequest( role, "addrole", roleAdded );

Anderson Cardoso

unread,
Mar 12, 2012, 12:53:40 PM3/12/12
to python-...@googlegroups.com
I use this:

On my Base handler:

class BaseHandler(tornado.web.RequestHandler):

    def return_json(self, data_dict):
        """
        acessory method to return json objects
        """
        self.set_header('Content-Type', 'application/json')
        json_ = tornado.escape.json_encode(data_dict)
        self.write(json_)
        self.finish()

On my app handler:

class SomeHandler(Basehandler):
   def get(self):
      # do something
      self.return_json(my_dict)

2012/3/12 Christopher Allick <chris...@gmail.com>



--
Anderson Pierre Cardoso
Computer Engineer - University of Sao Paulo

[gtalk]: apierre...@gmail.com
[blog]:  http://anderson-hacklife.blogspot.com/


"FreeSoftware -> free as in freedom"
  |  mande-me documentos em formatos livres (ODF) -> http://www.infowester.com/odf.php

Roey Berman

unread,
Mar 12, 2012, 2:38:16 PM3/12/12
to python-...@googlegroups.com
your return_json method is redundant, simply use RequestHandler.write()

Anderson Cardoso

unread,
Mar 12, 2012, 3:02:25 PM3/12/12
to python-...@googlegroups.com
I didn't know about that, Thanks Berman

2012/3/12 Roey Berman <roey....@gmail.com>

Daniel Truemper

unread,
Mar 15, 2012, 3:26:05 PM3/15/12
to python-...@googlegroups.com
Hi,

> I think the clue can be found by 'X-Requested-With' in request header.
>
> In tornado, maybe you can get this by
>
> self.request.headers.get('X-Requested-With')
>
> Please let me know if there is a better way.

I am using exactly this base on the `is_ajax` method in Django:

def is_ajax(self):
return "X-Requested-With" in self.request.headers and \
self.request.headers['X-Requested-With'] == "XMLHttpRequest"

Hth,
Daniel

Reply all
Reply to author
Forward
0 new messages