tags:

views:

142

answers:

2

Hi!

I was trying to understand how ajax works with django several times, but looks like no tutorials on the web can help me. I'd rather try to build a small sample. So trying to solve the following.

1) I have a very simple view function which returns random number on call e.g.

def homepage(request):
    id = randint(1, 6)
    return render_to_response("home.html", 
                              {"id" : id},
                              context_instance = RequestContext(request))

2) I have very primitive template, so it contains a number and button which triggers JS code on click e.g.

{% extends "index.html" %}

{% block head %}

<script type="text/javascript">
  <!--
      function clickNewButton()
      {
      window.open("/");
      }
      -->
</script>

{% endblock %}

{% block content %}
  <div id="meta">
    <form name="smallForm">
      <p>
         {{ id }}
      </p>
        <input type="button" value="New" onClick="clickNewButton()"/>
    </form>
  </div>

</div>

{% endblock %}

So basically the question is... How do I reload only the part of page which contains text of number

{{ id }}

in my case.


What will be the difference if I need to reload some other element with the click (e.g. image)?


Sorry if the question is just to silly. Not sure where to start... :(


also, how do I for example change not visible part of the page? e.g. one of the flashvars of swfobject instance, in case I dynamically reload flash application, to get new params?

+2  A: 

You can create a view which returns only the id

def id(request):
    return HttpResonse(randint(1, 6))

And load it with AJAX. For example, with jQuery:

$('#clickme').click(function(){ $('#randomnumber').load('/api/random.txt'); });

But if you need something bigger, create a full API with Piston ( http://bitbucket.org/jespern/django-piston/ ) and use it. And better learn jQuery first ;)

myfreeweb
Hey! Just small tip. How do I refresh flash object? After a click on the button.
Oleg Tarasenko
do you use SWFObject? also, do you really need flash? it's a big CPU eater
myfreeweb
+1  A: 

I'll repeat my standard answer to this question: use the jQuery Taconite Plugin. It's easy to setup, works seamlessly cross-browser, and it gives you amazing control over the entire page. It is a fire-and-forget solution in that all you do is send the request. All of the AJAXiness is handled for you and the all of the changes are applied automatically. Anything you can do with jQuery can be triggered with this plugin, up to and including causing an eval() of a chunk of Javascript (which can then, of course, do anything you like).

Because I've given this answer about 6 or 7 times now, I finally broke down and created a downloadable file with my Taconite class and a simple usage example. Let me know if you have questions and/or problems with it.

Peter Rowell