user1746291
user1746291

Reputation: 333

Issues with ajax in django

I'm using ajax in django first times .. I read some tutorials on the net and I'm trying to make a simple form which posts some information via ajax.

Here is my html form

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
function send_request()
{

 $.ajax({
                            type:"POST",
                            url:"/ajaxredirect/",


       });

}
</script>
<button type="button" onclick="send_request();">change content</button>

and it is my view

def Ajaxquery(request):
        if request.is_ajax():
                return HttpResponse("ok")
        else:
                return HttpResponse("error")

it does nothing when i am click on change content button in browser.

Any suggestions would be apperciated

Upvotes: 1

Views: 663

Answers (1)

John Rutledge
John Rutledge

Reputation: 672

Here is basic request/response setup I have made use of. I got the JSONResponse and AjaxResponse mixins from the Django Braces Module. I also made sure to include the following Django CSRF fix to prevent my AJAX request from being treated as a cross site request forgery.

JQuery:

<script type="text/javascript">
function send_request() {
    $.ajax({
        type: 'POST',
        url: '/ajaxredirect/',
        data: $('#your_form').serialize(),
        crossDomain: false,
        success: function(ctx) { console.log(ctx); },
    });
}
</script>

Views.py

from django.views.generic import View
from braces.views import JSONResponseMixin, AjaxResponseMixin

class AjaxResponseView(JSONResponseMixin, AjaxResponseMixin, View):
    def post_ajax(self, request, *args, **kwargs):
        data = request.POST.items() # form data
        ctx = {'hi': 'hello'}
        return self.render_json_response(ctx)

Upvotes: 1

Related Questions