views:

95

answers:

2

How can I detect whether a form was submitted via an AJAX post or just a browser submit in Pylons?

For example:

if 'name' in request.POST:
    #Do something

Would be true if 'name' was submitted via ajax or just a regular post. How can I differentiate?

Thank you.

+5  A: 

You can use request.is_xhr. This relies on your javascript framework to set the X-Requested-With: XMLHttpRequest header, but that's not bad since most frameworks like jquery add this header.

ThiefMaster
+1  A: 

I check for the accepts json in the request headers

def controller_accepts_json():
    return 'application/json' in request.headers.get('accept', '')
Rick
Sorry, too early in the morning. Of course this only works if you're making json requests and not an xml/html/text ajax request.
Rick
Additionally I'd never rely on clients sending proper accept-* headers.
ThiefMaster