I am trying to .append() the result of an AJAX call in my Laravel 5.4 application but the appending doesn't work and I get no errors in my console.
ajax.js:
$( document ).ready(function() {
$('#storeComment').on('submit', function(e) {
e.preventDefault();
// Retrieve form data
var formData = new FormData();
var data = $(this).serializeArray();
$.each(data, function(index, field) {
formData.set(field.name, field.value);
});
axios.post('/comments', formData, { headers: {'Content-Type': 'multipart/form-data' }}
).then(function(response) {
let newComment = "<div class='comment'><p><strong>" + response.data.user.name + "</strong>"
+ response.data.comment.created_at + "</p><p>" + response.data.comment.comment + "</p><hr></div>";
console.log(newComment);
$(".comments").append(newComment);
});
});
});
console.log(newComment);
result:
<div class='comment'><p><strong>admin</strong>2018-10-10 06:39:20</p><p>a</p><hr></div>
html:
<div class="comments">
@forelse ($imageRequest->comments as $comment)
<div class="comment">
<p><strong>{{ $comment->user->name }}</strong> {{$comment->created_at}}</p>
<p>{{ $comment->comment }}</p>
<hr>
</div>
@empty
<p>@lang('image_request.show.nocomments')</p>
@endforelse
</div>
The data is good, only the appending doesn't work unfortunately.
In your case error might have come but you haven't checked it: try to catch the error as below:
axios.post('/comments', formData, { headers: {'Content-Type': 'multipart/form-data' }}
).then(function(response) {
let newComment = "<div class='comment'><p><strong>" + response.data.user.name + "</strong>"
+ response.data.comment.created_at + "</p><p>" + response.data.comment.comment + "</p><hr></div>";
console.log(newComment);
$(".comments").append(newComment);
})
.catch(function (error) {
// handle error
console.log(error);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.