Answer the question
In order to leave comments, you need to log in
Html and javascript getting response before page load?
Hello! Situation. I'm loading likes for a post via AJAX using the POST method. There is a span on the page
<div class="pull-right"><i class="fa fa-heart" id="like" onclick="addlike(@Html.Raw(item.ID))"></i> <span id="[email protected](item.ID)" onload="getlike(@Html.Raw(item.ID))"></span></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
function getlike(id) {
var like = $('#like_' + id);
var count = 0;
$.ajax({
type: 'POST',
url: '/api/values/Getlike/' + id,
success: function (data) {
$('#like_' + id).text(data);
console.log('id: ' + id + 'data: ' + data);
}
});
}
});
</script>
Answer the question
In order to leave comments, you need to log in
I would remove "onload" and in the script below instead of:
document.addEventListener('DOMContentLoaded', function () {
function getlike(id) {
var like = $('#like_' + id);
// ...
}
});
$('span[id^="like_"]').each(function(index, like) {
var id = like.id;
// ...
});
You won't get likes anyway until you load jquery.
Therefore, at the time of issuing html to the browser, you should already have data in your span with the number of likes.
Alternatively, you can try to write a small script for sending and receiving a request without jquery in pure javascript ( https://learn.javascript.ru/ajax-xmlhttprequest for help) and load it at the top of the page.
Besides, what for to you in attributes to hang up handlers of events?
Hang listeners better with the $('#myid').on('click', listener) construct.
In the current implementation, it would have to be something like this:
$(document).ready(function() {
/** will start working when the DOM is ready, except for images **/
var id = item.ID, // I don't know where you get this item.ID from
$.ajax({
type: 'POST',
url: '/api/values/Getlike/' + id,
success: function (data) {
$('#like_' + id).text(data);
console.log('id: ' + id + 'data: ' + data);
}
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question