1

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

2
  • 1
    have you looked at firebug's net console, to see if there's an actual request sent? and if it was, what was the response for it? also the console tab in firebug will record if there are errors in your javascript code. Commented Nov 7, 2012 at 5:47
  • yes it gives me the 403 forbidden error but Now i have solved that and it works for me. Thanks for your suggestions and interest Commented Nov 7, 2012 at 5:51

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.