I have a django app. I'm typing a comment in a form and I'm sending it to my database via fetch.
my js code
document.getElementById("comment-form").onsubmit = function write_comment(e) {
e.preventDefault();
const sxolio = document.getElementsByName("say")[0].value;
fetch('/comment', {
method: 'POST',
body: JSON.stringify({
say: sxolio
})
})
.then(response => response.json())
.then(result => {
//print result
console.log(result);
});
my views.py
@requires_csrf_token
@login_required(login_url = 'login')#redirect when user is not logged in
def comment(request):
if request.method != 'POST':
return JsonResponse({"error": "POST request required."}, status=400)
new_comment = json.loads(request.body)
say = new_comment.get("say", "")
user = request.user
comment = Comment(
user = user,
say = say,
photo = Userimg.objects.get(user = user).image
)
comment.save()
return JsonResponse({"message": "Comment posted."}, status=201)
Next thing i wanna do is to display this comment and all the other data from my db, to my html page without refreshing.The moment i push the post button i want the comment to be dispayed. I dont want to update the page with some element.innerHTML = data.
my js code
function display_comments() {
fetch('/all_comments')
.then(response => response.json())
.then(all_comments => {
do some stuff
my views.py
@login_required(login_url = 'login')#redirect when user is not logged in
def all_comments(request):
all_comments = Comment.objects.order_by("-date").all()
print(all_comments[0].serialize())
return JsonResponse([comment.serialize() for comment in all_comments], safe=False)
If i use preventDefault i can see that my db is been updated but i can't retrieve the data. If i skip prevent default everything works fine but my page is refreshing simultaneously. Is there any way to do them both without refreshing the page?
The most likely problem is that your all_comments view request is being made before the comment has finished saving to the DB.
It is important that the response for comment is completely returned before the fetch to all_comments is started. You can accomplish this by doing the following...
function display_comments() {
fetch('/all_comments')
.then(response => response.json())
.then(all_comments => {
console.log(all_comments);
});
}
document.getElementById("comment-form").onsubmit = function write_comment(e) {
e.preventDefault();
const sxolio = document.getElementsByName("say")[0].value;
fetch('/comment', {
method: 'POST',
body: JSON.stringify({
say: sxolio
})
})
.then(response => response.json())
.then(result => {
// print result
console.log(result);
// The request to /comment has finished it is now safe to request all
// comments.
display_comments();
});
}