I am working on a project with django and jquery and i have to implement comments like facebook and i dont have idea how to do it. Please i need your help and need you to be very specific with the code because i am a newbie.
Here is the code please tell me what i am missing.
Javascript
<script type="text/javascript">
$(document).ready(function() {
$('#category_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url pos.views.add_category %}',
data: $('#category_form').serialize(),
dataType: 'json',
success: function() {
location.reload();
$('#category_form').get(0).reset();
},
});
return false;
});
});
</script>
Form
class CategoryForm(ModelForm):
name = forms.CharField(label=(u'Categoria'))
class Meta:
model = Category
Urls
url(r'^category/$', 'pos.views.Categories'),
View
def add_comment(request):
if request.method == 'POST' and request.is_ajax():
category_form = CategoryForm(request.POST)
if category_form.is_valid():
category = category_form.save(commit=True)
category.save()
json = simplejson.dumps(category, ensure_ascii=False)
return HttpResponse(json, mimetype='application/json')
return render_to_response(simplejson.dumps({'category': category,}), context_instance=RequestContext(request), mimetype='application/json')
Your view has two returns
Get rid of the one you don’t need. (It’s hard to tell what you need from the poorly formatted code.)
Read the jQuery docs here: http://api.jquery.com/jQuery.ajax/
Specifically, check out the Callback Function Queues section
Change your javascript so ajax does something like this instead:
This uses the success callback to set the returned data (the json returned from your view) as the html data of the element with the ID “results” in your HTML.