views:

134

answers:

2

I am trying to understand how Django + Jquery and Ajax calls work together.

It is just a simple /test/ url that shows a single input form, once submitted retrieves the answer from the server via ajax.

For that I have written a very small view:

def test(request):
    if request.is_ajax():
        from django.http import HttpResponse
        post_text = request.POST.get("post_data")
        return HttpResponse("{'response_text': '"+post_text+" recieved.'}", mimetype="application/json")
    else:
        return render_to_response('test.html', {},context_instance =RequestContext(request))

And I have written this url rule to my urlpattern at the urls.py:

(r'^test/$', 'myapp.views.test'),

And here is my test.html template:

<html>
  <head><title>template</title></head>

  <script type="text/javascript" src="/media/js/jquery.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
        $('#post_form').submit(function(event){
            event.preventDefault(); // cancel the default action
            var form = this;
            var data = {}
            data.post_data = $(form).find('input[@name=our_text]').val();

            $.post("/test/", 
                data, 
                function(responseData) {
                  alert(responseData.response_text);
                },
                "json"
            );
        });
    });
  </script>

  <body>
    <form id="post_form" method="post">
      INPUT: <input type="text" name="our_text" />
      <input type="submit" value="Add" />
    </form>
  </body>
</html>

It doesn't seem to do any reply on my www.mysite.com/test/ once I fill the input field and submit. What can be the problem?

+4  A: 

JSON keys to objects (dictionaries) must be quoted using double quotes ", not single quotes '. You really should use a real JSON library, such as simplejson (included with django at django.utils.simplejson) to generate your JSON.

Alex Gaynor
Thanks for your answer, I have checked the link but still confused how to apply simplejson to my view.
Hellnar
+2  A: 

jQuery 1.4 won't parse invalid JSON. As Alex Gaynor mentioned, your JSON is invalid, since it's using single quotes, rather than double quotes.

Writing JSON by hand is silly. Use a library to convert python datatypes to JSON. Again, as Alex mentioned, Django ships simplejson for you already. Alternatively, if you're using Python2.6 or later, json is part of the standard library http://docs.python.org/library/json.html

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

def test(request):
    if request.is_ajax(): 
        post_text = request.POST.get("post_data")
        response_dict = {'response_text': '"+post_text+" recieved.'}
        return HttpResponse(simplejson.dumps(response_dict), mimetype="application/json")
    else:
        return render_to_response('test.html', {},context_instance =RequestContext(request))
Josh Wright
now working, thanks for the snipllet!
Hellnar