How to pass data from ajax success and render in handlebars template?

Viewed 582

I am having this in .hbs file

                    <div class="col-12 col-md-3 order-md-1">
                        <div id="notes">
                            {{#each notes}}
                                {{>note}}
                            {{/each}}
                        </div>
                    </div>

Here is my jquery:

$.ajax({
    url: '/search/notes',
    method: 'GET',
    data: {
        search_string: 'server'
    },
    success: function(response) {
        var source = $('#notes').html()
        var template = Handlebars.compile(source)
        var context = {
            notes : response.notes,
        }
        var el_html = template(context);
        console.log(el_html)
        $('#notes').html(el_html)
    }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>

I am unable to get notes on id="notes". It results in blank div. Any help with this?

1 Answers

may be issue with your Ajax response. Below sample is working without Ajax.

setTimeout(function() {
var source = $('#notes').html()
var template = Handlebars.compile(source)
var context = {
    notes : ["test", "test2"],
}
var el_html = template(context);
console.log(el_html);
$('#notes').html(el_html);
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<div class="col-12 col-md-3 order-md-1">
                        <div id="notes">
                            {{#each notes}}
                                {{this}}
                            {{/each}}
                        </div>
                    </div>

Related