I’m working on making ordering by some criterias(e.g. by price, by author) on my jsp page. And using ajax to reload content of div when new sorting option is selected. But when reload function is called, it just hides div on web page.
I’ve checked out, that there are books in session scope needed to be shown and Jquery is included correctly.
This is html for choosing criterias to sort by:
<select>
<option id="default">Default</option>
<option id="price">By price</option>
<option id="author">By author</option>
</select>
And here is a code for processing click events for select element:
$(document).ready(function () {
$('select').change(function () {
$( "select option:selected" ).each(function() {
let sortAttr = $('option:selected').attr('id');
$.ajax({
// passing data to servlet
url: 'http://localhost:8080/sort',
type: 'GET',
// sort criteria
data: ({sort: sortAttr}),
// div needed to be reloaded
success: function () {
$('#mydiv').load(' #mydiv');
}
});
})
});
})
And code on jsp page for the div needed to be reloaded:
<div id="mydiv">
<c:forEach var="book" items="${sessionScope.books}">
<div class="col-4"><a href="/home?command=book_details&isbn=${book.ISBN}">
<img src="data:image/jpg;base64,${book.base64Image}">
<h4>${book.title}</h4>
<p>${book.price}$</p>
</a></div>
</c:forEach>
</div>
Any ideas why this happens?
EDIT
Finally, I found out what’s happenning. The important thing to notice(especially for me) in .load()
function is that whenever we call this function, it actually not just refreshes div content with new data, but makes request to the provided url and on that page(which url we provided) looks for the div
selector, gets it’s content and then goes back and inserts that content in current div
.
Notice, that If we don’t write url, .load()
function will make request to current page (correct me please, If I’m mistaken).
Hope that will help somebody!
2
Answers
First of all, you need to fix the typo in your code. Having space at the beginning of JQuery identifier won’t find the required element.
Change this:
$('#mydiv').load(' #mydiv');
To this:
$('#mydiv').load('#mydiv');
Also, I think you’re using it the wrong way.
Check the documentation here
How about