I have a POST request that passes data to my database when the form is submitted.
Photo of what I mean:
home.html
$(document).ready(function(){
var postForm = $(".form-post")
//POSTING DATA INTO DATABASE
postForm.submit(function(event){
event.preventDefault();
var thisForm =$(this)
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax({
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data){
console.log(data)
$(".form-post")[0].reset();
//I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH
$.ajax({
type: 'GET',
url: '{% url "postInfo" %}',
dataType : 'json',
success: function(cdata){
$.each(cdata, function(id,posts){
$('#cb').append('' +posts['fields'].title+ ' ' +posts['fields'].body+ '');
});
}
});
},
error:function(errData){
}
})
})
})
As it is now it shows multiple of the same posts every time I add a post.
This is my views
views.py
def postInfo(request): # GET REQUEST
if request.method == 'GET' and request.is_ajax():
mytitle = Post.objects.all().order_by('-date_posted')
response = serializers.serialize("json", mytitle)
return HttpResponse(response, content_type='application/json')
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
return HttpResponse('')
models.py
class Post(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
How can I make it so it just shows the post that I have added + what's in the database without showing multiple of the same posts? Thanks for any help.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)