Changing Dancer::Plugin::Ajax's content type

Dancer does lots of great things. It has a nice clean way to define routes to handle AJAX routes using the plugin Dancer::Plugin::Ajax.

ajax routes are defined in a clear way:

ajax '/stuff' => sub {
  # do work and return

This plugin technique allows for clear way to separate between ajax and other types of actions for the same route.

ajax '/stuff' => sub {
   # do ajax-y stuff here

get '/stuff' => sub {
   # handle html response

Unfortunately, the one negative with Dancer::Plugin::Ajax is that is assumes all responses will be XML.

A quick fix is to manually set the content type in each ajax handler.

ajax '/stuff' => sub {
   # do work
or add set it as a general option in your main before hook or in each prefix route handler like:
package WebApp;

hook before => sub {
   if ( request->is_ajax ) {

Both of these solutions feel kind of clunky due to the level of duplication. Our app returns JSON or HTML snippets and never uses XML. This redundancy in code led me to creating a patch for Dancer that allows default Ajax content_type to be set in the config file. (see issue 840).

Config Example:

      content_type: 'application/json'



  1. Great Article
    Cloud Computing Projects

    Networking Projects

    Final Year Projects for CSE

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training


Post a Comment

Popular posts from this blog

BootstrapX clickover

Template Toolkit Debugging inside of Perl Dancer

2 ways to get SQLite to put dates into columns