Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Post in Django framework?

I put together a simple test of an ajax/jquery post within a django framework, but don't really understand why the output doesn't make it to a template page. Anyone?

I can see the contents of the post in firebug's 'response' tab, but whether I try to return a template or a simple message, nothing happens in the browser itself. Conversely, a non-ajax post works as expected (loads new page, posts message)

I'm a complete newbie to ajax/jquery/django so please excuse my ignorance :)

Eventually, what I'd like to be able to do is to pass arbitrary, non-form variables to a django view via jquery. Possible? Thank you :)

Here's the code --

test.html:

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
   $(document).ready(function() {
       $("#testForm").submit(function(event){
           event.preventDefault();
           $.ajax({
                type:"POST",
                url:"/test_results/"
                    });
       });
       return false;
    });
</script>
</head>
<body>
        <form id="testForm" action="/test_results/" method="post">
            <input type="submit" id="go" name="go" value="Go!">
        </form>
</body>
</html>

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse


    def test_ajax(request):
        if request.is_ajax():
            message = "Yes, AJAX!"
        else:
            message = "Not Ajax"
        return HttpResponse(message)
        #alternative test: return render_to_response('test_results.html')

urls.py:

(r'^test_results/$', views.test_ajax),
(r'^test/$', views.test),

and the almost empty test_results.html:

<html>
<head>
</head>
<body>
test results
</body>
</html>
like image 527
Igor Avatar asked Mar 14 '11 21:03

Igor


2 Answers

I can see the contents of the post in firebug's 'response' tab, but whether I try to return a template or a simple message, nothing happens in the browser itself. Conversely, a non-ajax post works as expected (loads new page, posts message)

If you're getting a response, you're getting a response. You're just not doing anything with it.

Why not alert the data and append it to the <body> for example:

$.ajax({
     type:"POST",
     url:"/test_results/",
     data: {
            'arbitrary-data': 'this is arbitrary data',
            'some-form-field': $("myform input:first").val(), // from form
            'background-color': $("body").css("background-color")
            // all of this data is submitted via POST to your view.
            // in django, request.POST['background-color'] 
     },
     success: function(data){
         alert(data);
         $("body").append(data);
     }
});
like image 57
Yuji 'Tomita' Tomita Avatar answered Sep 19 '22 22:09

Yuji 'Tomita' Tomita


You need to add a handler for the response returned by the view:

$.ajax({
    type:"POST",
    url:"/test_results/",
    dataType: "json",
    success: function(json)
    {
        //specifying a dataType of json makes jQuery pre-eval the response for us
        console.log(json.message);
    }
 });

You'll probably also want to encode the response as JavaScript in your view:

try:
    import json
except ImportError:
    import simplejson

def my_view(request):
    if request.is_ajax():
        return HttpResponse(json.dumps({'message' : 'awesome'},
            ensure_ascii=False), mimetype='application/javascript')

Hope that helps you out!

like image 21
Brandon Avatar answered Sep 18 '22 22:09

Brandon