Search code examples
jquerythymeleaf

Reload div with new attributes


I have a div:

<div class="textWord_about" data-link="first">
  <br/><br/>
  <br/><br/><br/>
  <div class="col-xs-12"></div>
  <table class="table table-hover">
    <thead>
    <tr style="margin-right:0;">
      <th>Username</th>
      <th>Follower Number</th>
      <th>Following Number</th>
      <th>Profile</th>
      <th>Created At</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="follower:${followers}" style="margin: 0 auto;">
      <td th:text="${api.getHash(follower.getScreenName())}"></td>
      <td th:text="${follower.getFollowersCount()}"></td>
      <td th:text="${follower.getFriendsCount()}"></td>
      <td><a th:href="@{'/viewprofile'(id=${follower.getId()})}">profile</a></td>
      <td th:text="${follower.getCreatedDate()}"></td>
    </tr>
    </tbody>
  </table>
</div>

I used Jquery and Ajax to get a new value for followers from the server. The problem is that how can I set this new value using Jquery?

I have tried something like this:

$('.textWord_about[data-link=' + $(this)
    .data('button-link-followerList') + ']')
    .attr('followers', data.followers);

the Script with Ajax request is this:

$(function () {
    $(".button-link-followerList").click(function () {
        event.preventDefault();
        var $post = $(this);
        var href = $($post).attr("id");
        var currentCredit_followerList = parseInt($('#_followerList_credit').text());
        console.log("herf: " + href);
        if (currentCredit_followerList != 0) {
            console.log("condition checked!");
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: href,
                dataType: 'json'
            }).done(function (data) {
                if (data.status == "success") {
                    var newCredit_followerList = currentCredit_followerList - 1;
                    $('#_followerList_credit').text(newCredit_followerList);
                    $('.mainContainer').hide();
                    $('.textWord_about > table > tbody > tr').remove();

                    $.each(followers, function (index, obj) {
                        var row = '<tr>' +
                            '<td>' + obj.screenName() + '</td>' +
                            '<td>' + obj.followersCount + '</td>' +
                            '<td>' + obj.friendsCount + '</td>' +
                            '<td><a href="/viewprofile' + '?id=' + obj.id + '">profile</a></td>' +
                            '<td>' + obj.createdDate + '</td>' +
                            '</tr>';
                        $('.textWord_about > table > tbody').append(row);
                    });

                    $('.textWord_about[data-link=' + $(this).data('button-link-followerList') + ']').fadeIn({width: '200px'}, 300);
                    return false;
                }
                else if (data.status == "ratelimit") {
                    window.location.href = "ratelimit";
                }
            });

        } else {
            // Show Alarm!
            $('#_credit_error').fadeIn(100);
        }
    })
});

But, the console log says that the followers is undefined. As a result, I can not see my div with its new value.

Note: In the very first load the page which contains the div, it is hidden and the followers does not have any value.


Solution

  • The th: attributes guide Thymeleaf, how to render some static elements in the output html, but don't provide any special attributes. When you check the page's source using the web browser's inspector, you will see an oridnary content inside <tbody>, without any followers e.g.

    <tr>
        <td>John Doe</td>
        <td>10</td>
        <td>100</td>
        <td><a href="/viewprofile?id=1">profile</a></td>
        <td>01-08-2017</td>
    </tr> 
    

    You receive JSON from server so if you want to add/replace values you have to manipulate DOM using jQuery. You can take advantage of jQuery methods remove(), each() and append()

    Firstly remove old rows (if you want to replace old followers with the new ones) .

    $('.textWord_about > table > tbody > tr').remove();
    

    Secondly iterate through followers' list, which you've received from server. For each object append new row with suitable data.

    $.each(data.followers, function(index, obj) {
        var row = '<tr><td>' + obj.screenName() + '</td><td>' + obj.followersCount + '</td><td>' + obj.friendsCount + '</td><td><a href="/viewprofile' + '?id=' + obj.id + '">profile</a></td><td>' + obj.createdDate + '</td><td></tr>';
        $('.textWord_about > table > tbody').append(row);
    });
    

    This should resolve your issue.

    Note: I used Thymeleaf syntax inside the script ([[ @{'/viewprofile'} ]]) to evaluate proper link adress, so please remember to put the entire script into the tag with js inlining: <script th:inline='javascript'>.

    Note I hardcoded URL to profile view and this should be fine. Otherwise, if you want to evaluate them using thymeleaf's @{} syntax, you have to apply workaround. Provide an inline script inside html file, which evaluates your url and assign it to the variable:

    <script type="text/javascript" th:inline="javascript" >
        var viewprofileUrlPrefix = [[ @{'/viewprofile'} ]]
    </script>
    

    and then simply use that variable in your js file while appending:

    '<a href="' + viewprofileUrlPrefix + '?id=' + obj.id
    

    Note2: I skipped the part with api.getHash( ... ) as I don't know what it is doing. I assumed that received JSON would contain the proper value, so you don't have to evaluate it via javascript. This would be the most convenient.