a better way to do ajax in django

By : Joel
Source: Stackoverflow.com

The other day I wrote some AJAX for a Django app that i have been working on.

I come from Ruby on Rails, so I haven't done much in the way of raw JS.

So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:

1) JS function using prototype's Ajax.Updater ('tablediv' being the id of the table i wanted to update Ajaxily, and url pointing to the proper django view)

 function updateTable(){
       new Ajax.Updater('tablediv',url {params: params....etc

2) django view that got new data to populate the table with:

 def ajaxTable
     objects = Objects.object.all...
     return render_to_response('ajaxtable.html',objects)

3) ajaxtable.html was just a sort of Rails "partial" so basically a table w/o <table> </table> ...:


so to my actual question:

This seemed hacky to me, I sort of threw it together after getting tired of searching online for what i wanted.

Is this the way it's done? It works fine, I just don't know enough to know, you know?

By : Joel


What exactly seems hacky about it? Seems like a perfectly valid way of doing something.

I guess an alternative would be serialising to json and sending it back to a javascript templating snippet.

By : Steerpike

No matter what, you're going to need at least two things:

  1. Your javascript code to make the call (you have this)

  2. Server side code to handle the request (this is your view and url-config)

There is absolutely nothing "hacky" about this.

The third thing, your template file, is optional - but is generally good practice. You want to separate your markup from the code, for many reasons.

So I think you've got the right idea. Carry on.

This video can help you solving your question :)
By: admin