How to achieve string interpolation while appending html inside a div using Javascript

3.3k Views Asked by At

Might be a silly question but here it is. I am trying to insert some html inside my div based on data received from my backing java controller. It all works fine but I am not aware how to interpolate strings from the data I receive into the paragraph tag of my jsp.

Here is the code

<script>
    $(document).ready(function() {
        var url = "${context}/support/ajax";
        $.ajax({
            type : 'GET',
            url : url,
            dataType : 'json',
            success : function(data, status, xhr) {

                data.forEach(function(data) {
                    if (data.userType == 'O') {
                        $( ".chats" ).append(`
                                <div class='chat-avatar'>


                                <a class='avatar' data-toggle='tooltip' href='#'
                                    data-placement='right' title='' data-original-title=''> <img
                                    src='<c:url value = '/app-assets/images/portrait/small/avatar-s-1.png'/>'
                                    alt='avatar'>
                                </a>
                            </div>
                            <div class='chat-body'>
                                <div class='chat-content'>
                                    <p>{data.comment}</p> // **This is what I want to achieve**
                                </div>
                            </div>
                                `);

                    } 

                });
            }
        });

    });
</script>

The above ajax call works fine an I do receive data. Also, I am able to insert this html into the appropriate div element. Now I want to insert the data.comment value inside the p element .

How do I do this ?

EDIT --1

After using `${expression}` syntax, the <p> tag comes as blank in the broswer console while clearly the value is present.

dev tools

EDIT--2

I don't know why but "<p>"+d.comment+"</p>" is working. But not interpolation.

2

There are 2 best solutions below

3
KevBot On

Because you are using the back-tick (`) you are close to using template strings. You just need to use placeholders correctly:

const data = {comment: 'The comment'};
const result = `...<p>${ data.comment }</p>...`;

console.log(result);

Documentation on Template Strings

1
Ilyas Assainov On

I can see you're using the data variable for both the ajax response and the current value of data in the loop. Are you sure you're referencing the correct object?