Reputation: 647
I kinda wrote ajax function(followed some tutorial on youtube), but not sure what to write in success part. if I do alert('it worked') it just shows it worked but the form is not going through. What I'm trying to do is sending comment without refreshing the page by ajax function. If someone can tell me what I should do in my success function, i would highly appreciate the help, thank you. I have two forms.
<form method="POST" action='{% url "comment_create" %}' class='commentForAjax'>{% csrf_token %}
<input type='hidden' name='post_id' value='{{ post.id }}'/>
<input type='hidden' name='origin_path' value='{{ request.get_full_path }}'/>
{% crispy comment_form comment_form.helper %}
</form>
<div class='reply_comment'>
<form method="POST" action='{% url "comment_create" %}'>{% csrf_token %}
<input type='hidden' name='post_id' id='post_id' value='{% url "comment_create" %}'/>
<input type='hidden' name='origin_path' id='origin_path' value='{{ comment.get_origin }}'/>
<input type='hidden' name='parent_id' id='parent_id' value='{{ comment.id }}' />
{% crispy comment_form comment_form.helper %}
</form>
</div>
<script>
$(document).on('submit','.commentForAjax', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/comment/create/',
data:{
post_id:$('#post_id').val(),
origin_path:$('#origin_path').val(),
parent_id:$('#parent_id').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
alert('it worked');
}
})
})
</script>
backend code
#Comments
urlpatterns += patterns('comments.views',
url(r'^comment/create/$', 'comment_create_view', name='comment_create'),
)
comment views.py
def comment_create_view(request):
if request.method == "POST" and request.user.is_authenticated():
parent_id = request.POST.get('parent_id')
post_id = request.POST.get("post_id")
origin_path = request.POST.get("origin_path")
try:
post = Post.objects.get(id=post_id)
except:
post = None
parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None
if parent_comment is not None and parent_comment.post is not None:
post = parent_comment.post
form = CommentForm(request.POST)
if form.is_valid():
comment_text = form.cleaned_data['comment']
if parent_comment is not None:
# parent comments exists
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=parent_comment.get_origin,
text=comment_text,
post = post,
parent=parent_comment
)
#affected_users = parent_comment.get_affected_users()
#print "this is"
affected_users = parent_comment.get_affected_users()
return HttpResponseRedirect(post.get_absolute_url())
else:
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=origin_path,
text=comment_text,
post = post
)
return HttpResponseRedirect(post.get_absolute_url())
else:
messages.error(request, "There was an error with your comment.")
return HttpResponseRedirect(origin_path)
else:
raise Http404
Upvotes: 0
Views: 65
Reputation: 1095
Using $.ajax
with POST does not post a form, but posts the data you send in that method. You need to choose which method to use, not both as you have done. Your code taps into the form's submit, prevents it, then uses XmlHttpRequest to post the data instead. Why not remove your forms and just use your $.ajax
implementation when the user clicks a button?
You are also not required to use the success()
callback.
Edit
If you use forms, then you need some way to submit the form. Usually a 'submit' type input. This will do a post to the form's target url.
If you use ajax, you don't need forms (or any element's name
attribute), but you do need some kind of action/event that will trigger the use of that ajax POST. This is also usually a click of a button, or a select onchange. So instead of
$(document).on('submit','.commentForAjax' ... etc
which handles the submit event of the form, you can use a similar handler for a button's click.
$("#buttonId").on("click", function() {
//Call $.ajax POST here
});
Upvotes: 1
Reputation: 5800
There's a django+jquery chat system tutorial on YouTube. This uses AJAX to send the messages. You can get an idea from this tutorial and optimize your code based on that. https://www.youtube.com/watch?v=Z8Gjm858CWg
The tutorial could be a bit confusing but you will find the GitHub repository link on the video description. Download the code and work from there.
Upvotes: 0