i am trying to make website using Laravel 10 and i have added comment option for users so they can leave comment on any post but the problem is when use add comment on post the page scroll to top even if user leave comment on 20th post. so it is difficult for use ro go back where he left..
this is my code for add comment
@auth
<div class="comment-box mt-2">
<form id="commentForm" action="{{ route('comments.store') }}" method="POST">
@csrf
<input type="hidden" id="post_id" name="post_id" value="{{$post->id}}">
<input type="hidden" id="user_id" name="user_id" value="{{ Auth::user()->id }}">
<div class="position-relative mt-4">
<textarea name="content" placeholder="leave a comment" required class="form-control" style="padding-right: 30px; border-radius: 10px; height: 40px;"></textarea>
<button type="submit" class="position-absolute" style="border: none; background: none; right: 10px; top: 50%; transform: translateY(-50%);">
<i class="fas fa-paper-plane"></i>
</button>
</div>
</form>
</div>
@endauth
and this is script
<script>
$(document).ready(function() {
$('#commentForm').on('submit', function(event) {
event.preventDefault(); // Prevent the default form submission
// Collect form data
var formData = $(this).serialize();
// Debugging: Log form data to ensure it is correct
console.log('Form data:', formData);
// Perform the AJAX request
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: formData,
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val(),
'Accept': 'application/json'
},
success: function(data) {
// Debugging: Log the response from the server
console.log('Server response:', data);
// Handle successful form submission (e.g., display a success message)
// Optionally, clear the textarea or display the new comment
},
error: function(error) {
// Debugging: Log any error from the server
console.error('Error:', error);
// Handle form submission errors
}
});
});
});
</script>
i have tried various method from online and AI but still not works..
2
Answers
you can handle the success response
add this code in success response
var newComment =
<div class="comment"> <p>${data.content}</p> <small>Posted by: ${data.user.name}</small> </div>
;$(‘.comment-box’).append(newComment);
Since this form appears once per post, you could use the post’s
id
write the ids.