1

Looking to get some insight and tips on using ajax with django.

Say I have a function:

def add_comment(request, pk):
  if request.method == 'POST' and request.is_ajax():
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
      comment = comment_form.save(commit=True)
      comment.save()
    json = simplejson.dumps(comment, ensure_ascii=False)
   return HttpResponse(json, mimetype='application/json')
  return render_to_response({{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')

and I'm trying to post the comments to a page without a redirect with ajax function:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
  $(document).click(function()
  {
   $('#comment_form').submit(function()
   {
    var dataString = $('#comment_form').serialize();
    $.ajax({
      type: 'POST',
      url: '',
      data: dataString,
      success: function(data){
        $('').html(data);
      },
    });
    return false;
    });
  });

</script>

I believe I'm mixing up a few things here. I am trying to get the page to load comments without a redirect. I don't need an exact answer, maybe just steered in the right direction.

4
  • I asked to get insight and tips on using ajax with django to post comments. Its at the top of the post, was it not clear? Commented Feb 25, 2012 at 3:10
  • Are you familiar with django and ajax, I looked at your profile and it seems as though you only answer questions with matplot. If you have some insight, please share. Commented Feb 25, 2012 at 3:30
  • I have very little experience with django and Ajax, sorry, but I was left with he impression that your question was vague. I could be wrong. You're right that I've focused on matplotlib questions, and I've had most success answering them when they were specific: why doesn't xxx work? Commented Feb 25, 2012 at 3:51
  • I truly appreciate the response. As you can probably tell I am very new to the site. I will definitely keep this in mind, for the future. Commented Feb 25, 2012 at 4:23

2 Answers 2

2

This can helps:

this could be your view:

import json

def add_comment(request, pk):
    if request.method == 'POST' and request.is_ajax():
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=True)
            comment.save()
            json_response = json.dumps({"status":"Success"})
            return HttpResponse(json_response)
        errors = {}
        for k, v in job_type_form.errors.items():
            errors[k.capitalize()] = v
        response = {
            'success': False,
            'errors': errors
        }
        return HttpResponse(json.dumps(response))

and your jquery could be like this:

$('#comment_form').submit(function() {
    var dataString = $('#comment_form').serialize();
    $.ajax({
        type: 'POST',
        url: '',// you need to put this to something like '{% url to_your_view %}'
        data: dataString,
        dataType: 'json'
        success: function(data){
            // you can access to your json object like data.status or data.something
            $('').html(data.status);
        },
    });
    return false;
});
Sign up to request clarification or add additional context in comments.

7 Comments

Hey, thanks for the response first off. I'm going to tinker with this code. As for the comments on the ajax function dealing with the url to view, I had put in "{{ post.id }}" but, this didn't work. I'm trying to post the comments right to the page without a redirect. I've found a lot of information that will return me to a success page, I've already been able to get comments to post but, I only with a redirect to a main page.
Tried this out and tinkered around with it, still didn't work. I'm going to go over everything again.
there is no error.. could you please tell me what is wrong?? what error did you get??
I believe dataType: json needs quotes
I haven't tried out the part of the function for return errors. I know the modelform isn't saving but, on firebug I see the post goes through.
|
0

Thanks for the posts I finally got things worked out. The jquery was the main issue.

$(document).ready(function() {
  $('#comment_form').submit(function(e) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: '{% url art.views.post %}',
    data: $('#comment_form').serialize(),
    dataType: 'json';
    success: function(){
      location.reload();
$('#comment_form').get(0).reset();
  },
  });
  return false;
  });
});

I was sending the DOM object not the actual form data to the view.

In the view I combined two functions to get the two sharing the same URL.

def post(request, pk):
  post = Post.objects.get.(pk=int(pk))
  comments = Comment.objects.filter(post=post)
  _dict = dict(post=post, comments=comments, form=Comment_form(), user=request.user)
  _dict.update(csrf(request))
  cf_obj = Comment(post = Post.objects.get(pk=pk))
  if request.method == 'POST' and request.is_ajax():
    if comment_form.is_valid():
      comment = comment_form.save(commit=True)
    else:
      raise Http404
    response = serializers.serialize('json', [comment])
    return HttpResponse(response, mimetype='application/json')
  return render_to_response('post.html', d)

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.