1

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!

  • Hi, why you need ajax here ? are you changing something inside your `DOM` from server ? Also , what you expect this - > `$('#mydiv').load(' #mydiv');` to do ? – Swati Jan 23 '21 at 12:44
  • Hi! Yes, It's a bit strange, but I didn't find a solution how to do it in DOM. I'm sorting elements which are stored in HttpSession. If I had an ability, I would sort them inside DOM. And here `$('#mydiv').load(' #mydiv');` I thried to reload div with old data, once new data is recieved from server –  Jan 23 '21 at 13:01
  • 1
    So inside your servlet you are setting new value in session .. why not return that `list` as json form and build that htmls inside your `ajax success` ? Check [this](https://stackoverflow.com/a/4113258/10606400) answer . Onces you tried that let me know if you get any errors . – Swati Jan 23 '21 at 13:05
  • Also, if you need to be your response to be reloaded to show new content then [this](https://stackoverflow.com/questions/18490026/refresh-reload-the-content-in-div-using-jquery-ajax) should work . – Swati Jan 23 '21 at 13:12
  • I'm using JSTL on jsp page, so it is more convenient for me to put an object to session, otherwise, I have to rebuild some logic of my application. Unfortunatelly, [this](https://stackoverflow.com/questions/18490026/refresh-reload-the-content-in-div-using-jquery-ajax) link didn't solve the issue –  Jan 23 '21 at 14:21
  • Did you tried like this : `$("#mydiv").load(location.href + " #mydiv");` ? – Swati Jan 23 '21 at 15:12
  • Yes, sure. I've tried it. I don't know what to do... I'm struggling with it 2 days... –  Jan 23 '21 at 15:14
  • Can you show server page code ? I will replicate this on my end – Swati Jan 23 '21 at 15:16
  • It is 200. But I don't understand why almost similar code works fine on other pages, and not here... –  Jan 23 '21 at 15:25
  • why are you doing `$('#mydiv').load(' #mydiv');`? Why is the sort code not returning the new content? – epascarello Jan 23 '21 at 17:25
  • Using this peace of code `$('#mydiv').load(' #mydiv');` I'm trying to reload div –  Jan 23 '21 at 17:45
  • Thanks! The [link](https://stackoverflow.com/a/4113258/10606400) you provided was very useful –  Jan 27 '21 at 14:18

2 Answers2

0

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

Mazen Ak
  • 152
  • 7
  • I've removed estra space, as you said and that didn' fix the problem. And when I used `$('#mydiv').load()`, I got *Uncaught TypeError: Cannot read property 'indexOf' of undefined* –  Jan 23 '21 at 13:13
  • Have you checked the documentation about how it works? Also, [this](https://stackoverflow.com/a/25373840/10743722) would be helpful too. – Mazen Ak Jan 23 '21 at 13:28
  • Yes, I have checked the documentation, changed code to `$('#mydiv').load('#mydiv');`, but this still haven't solved the problem. And what do you mean by saying `Also, I think you're using it the wrong way`? –  Jan 23 '21 at 14:09
  • You need to provide a `url` to `.load` - it looks like you want `$("#mydiv").load(url + " #mydiv")` – freedomn-m Jan 23 '21 at 14:56
  • I have already tried it, but unsuccessfully. The thing is, that on other jsp this works fine. What is surprising, is that when .load() is called, *mydiv* content disappears –  Jan 23 '21 at 17:03
  • Thank you for the answer! Finally, I finished struggling with it by making myself fully understand documentation –  Jan 27 '21 at 14:16
0

How about

$(function() { // on page load
  $('select').on("change", function() { // when the select changes
    let sortAttr = $('option:selected', this).map(function() {
      return $(this).attr('id')
    }).get(); // get an array of selected IDs
    if (sortArrr.length > 0) {
      $('#mydiv').load('http://localhost:8080/sort?sort=' + 
        sortAttr.join(',') + // make a comma delimited string
        ' #mydiv'); // copy myDiv from the result
    }
  });
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Sorry, I'm new to Javscript... Can you explain a little bit what's going on here? –  Jan 23 '21 at 14:30
  • @Donny I have modified a little (why ajax if nothing selected) and added comments – mplungjan Jan 23 '21 at 14:42
  • Sorry, that didn't figured the problem out. But, thanks for explanation. –  Jan 23 '21 at 14:50
  • Your server needs to handle a comma separated list of IDs instead of what you do now – mplungjan Jan 23 '21 at 14:51
  • Okey, let it be. But the problem is that *mydiv* element hides at all after load function is called –  Jan 23 '21 at 14:54
  • 1
    Right click on the div and click inspect and see why. Perhaps it is empty or your JSP gives error – mplungjan Jan 23 '21 at 14:56
  • I've inspected the code in devTools, and noticed, that the is *still* presents old data, and div is not shown –  Jan 23 '21 at 15:01
  • And in the network tab calls the jsp correctly? – mplungjan Jan 23 '21 at 15:02
  • I told you incorrect information about whether data is present in mydiv on *elements* tab. So, no, there is no data in div –  Jan 23 '21 at 16:17
  • So look in the network tab to see if the server process returns anything – mplungjan Jan 23 '21 at 16:18
  • 1
    Thanks for the answer, the problem was, that I didn't understand documentation fully. The important thing to notice(especially for me) was that when we call function .load(), it actually not just refreshes div content, but makes request to the provided url and on that page looks for the div, gets div content and then goes back and inserts that content in current div –  Jan 27 '21 at 14:15