I have a web app that contains this template which renders a number of books using the returnd books from the server which is implemented using python(flask) the titles of the books, IDS, and authors' names all of these are in the variable "books" which as you can see here I loop over to print all of that. I also give the users the ability to rate the books, but When the user rate a book I'm sending an ajax request, I'm getting back only the rate of the book that just gets rated. I'm trying to append every rate to its book, the problem in my code is that if the user tried to rate again the new get concatenated with the old rate (i.e if the old rate is 3 and the user rate again with 4 the book's rate will be 34). I tried to use replaceWith but 8 got undefined.
Here is the javascript code:
<script>
jQuery(function ($) {
$(".book-rating").on("change", function (event) {
const $target = $(event.target);
const rating = $target.val(); // value of select.
const bookId = $target.next().val(); // value of input
// console.log(bookId);
// console.log($(this).attr('book-rating'));
var $rated = this.form.querySelector(".rated");
$.ajax({
url: /rate/${bookId}/${rating},
success: function(all_rates){
console.log('success', all_rates);
$.each(all_rates, function(i, r){
// if(this.form.querySelector(".rated")
$rated.append(r.rate);
});
}
});
});
});
</script>
Here is the HTML
<div
style="background-color:#6e6b64" >
{% if book.volumeInfo.imageLinks.smallThumbnail %}
<img src="{{book.volumeInfo.imageLinks.smallThumbnail}}">
{% endif %}
<div >
<h5 style="color:red" >{{book.volumeInfo.title}}</h5>
<p style="color:blue" >{{book.volumeInfo.authors}}</p>
<form style="margin-bottom:5px" action="/addcomment" method="get">
<h4 ></h4>
<input name="book" type ="hidden" id="book_id" value="{{book.id}}" type="text">
<a href="{{book.volumeInfo.infoLink}}" >More Info</a>
<button type="submit" >add comment</button>
<!--get the user rate-->
<label >
Give your rate
<select style="width:200px;" >
<option value="">rate</option>
<option value="1">1</option>
<option value="2">2</option> <option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input name="book" type="hidden" value="{{book.id}}" type="text">
</label>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
CodePudding user response:
Calling .append on an Element will, as described by MDN, insert "a set of Node objects or DOMString objects after the last child of the Element"
If you want to replace the content instead, try using .innerText (for text-only content) or .innerHTML (if you need to include markup)
So your code would change to:
...
$rated.innerText = r.rate;
...