About Archive Tag Cloud Translations RSS

You are writing a comment about Intro to Unintrusive JavaScript with Django, here is a quick summary:

The steps of the novice web developer are fraught with peril. They begin with HTML, then move onto CSS. They learn a web framework or two, and they finally start to wrangle with JavaScript. This tutorial aims to help the developer who has taken their first steps with Django, and wants to begin experimenting with adding JavaScript and Ajax to their webapps.


You are responding to this comment written by Chuck on September 21st 2008, 18:14.

Debugging can be tough with Ajax and Django. When there is an error in the python code, you do not get the usual crash page.

One solution is to capture the crash and return it with ajax. You can then display the python error on your webpage.

Here is the code I use for all ajax calls:

from django.http import HttpResponse
from django.utils import simplejson

def process_ajax(request,func,debug=False):

    '''request.POST should contain:
        'json_str' - the value should be string containing the json
            serialization of the javascript data

      func = a function that accepts the json string and returns a
             dictionary
    '''
    response_dict={'traceback':''}
    if debug:
        post_data=simplejson.loads(request.POST['json_str'])
        response_dict.update(func(post_data))

    else:
        try:
            post_data=simplejson.loads(request.POST['json_str'])
            response_dict.update(func(post_data))
        except:
            import traceback
            import cStringIO
            fp=cStringIO.StringIO()
            traceback.print_exc(file=fp)
            txt=fp.getvalue()
            response_dict['traceback']=txt
            fp.close()

    return HttpResponse(simplejson.dumps(response_dict),mimetype='application/javascript')

Here is the corresponding javascript ( I use the YUI libraries) :

var callback =
{
  success: function(o){
    var response_obj=YAHOO.lang.JSON.parse(o.responseText);
    if (response_obj.traceback != ''){
       alert('Python error. Traceback: '+response_obj.traceback);
    }
  },

  failure: function(o){
   alert('Unknown error.');
  }
}


function func(id)
{
var myData={'id':id}
var postData='is_xhr=1&json_str='+YAHOO.lang.JSON.stringify(myData);
var request = YAHOO.util.Connect.asyncRequest('POST', '.', callback, postData);
}


Please be aware that comment forms go stale after one hour.





Comments may make use of LifeFlow MarkDown. Raw html will be escaped.


Quick Introduction to LifeFlow MarkDown Syntax

A highlighted code block:

@@ ruby
def a (b, c):
  b * c
end
@@

Other common languages work as well: scheme, python, java, html, etc.

Other markdown syntax:

 ### This is an h3 title
#### This is an h4 title
**this is bold**
*this is italics*

1. This is an
2. ordered list

* And an unordered
* list too

[this is a link](http://www.lethain.com/ "Lethain")