Posts Tagged ‘Ajax’

Check for ajax requests in Pylons

In todays world of web development Ajax is taken for granted and there is a ton of good JavaScript frameworks out there that makes Ajax development quite easy and enjoyable. Together with a nice MVC framework it is even better. Each framework has its own way of detecting Ajax calls or more correctly xmlHttpRequests, which is a huge topic on its own.

For checking if a request is an Ajax request in Pylons you just use is_xhr in your controller, this is based on the fact that you are running your Pylons app as wsgi.

Make sure your importing the request class

from pylons import request

Then in your controller function you can just do

# Checks if request is a xmlHttpRequest (Ajax) and returns a def
if request.is_xhr:
 
# Code goes here
 
return render_mako_def('template_path',"def_name")

You can also return and render a full template if you need or think that works better with your function.

More information can be found at PylonsHQ Paster – Documentation – WSGI, CLI scripts