If this is a redundant question please let me know and point me there, but I am not finding the exact question/answer combination nor a mixture of the two.
I have some ajax in jquery that calls a function from a php page. Without the handlebars the json data comes back nice and pretty. No issues there. However I can't seem to get ajax to write out my results to a handlebars template. Here is the code I have now:
$.ajax({
type: "post",
url: "../includes/db_functions.inc.php",
data: ({ p : p, p2 : p2, f : f }),
dataType: "json",
success: function(results){
$.each(results, function(i, item){
var context = [
{
id : item[i].id,
clock_number : item[i].clock_number,
}
],
template = Handlebars.compile( $('#template').html() );
$('table.entries').append( template(context) );
});
}
});
anyone know what I might be missing here? I 99% sure its in the context area, but just not finding it.
[edit]
<table class="entries">
<script id="template" type="text/x-handlebars-template">
<tr>
<td>{{id}}</td>
<td>{{clock_number}}</td>
</tr>
</script>
</table>
From Handlebars - Getting Started, I would say, leave out the array and use just the object as context
var context = {
id : item[i].id,
clock_number : item[i].clock_number,
},
template = Handlebars.compile($('#template').html());
$('table.entries').append(template(context));
In the ajax success
code, there's the call to $.each(results, function(i, item) {...})
. In this context, item
is already the i
th element, if results
is an array. Maybe you can reduce this to
success: function(results) {
var template = Handlebars.compile($('#template').html());
$.each(results, function(i, context) {
$('table.entries').append(template(context));
});
}
Ok so there were actually several things wrong here.
First I had a typo in the form itself, although it did not fix the issue would have caused me not to find the fix.
Second, couldn't use the $('#submit').on("click", function()) for some reason it just didn't like it. I changed it to a $('#textbox).on("blur", function()) and immediately started getting results from the success function.
Third, yeah ok I don't know if this was actually an issue, but it works so I'm calling it part of the answer. Do what @Olaf Dietsche with the $.each, something like this:
$.each(results, function(i, context){
$('div.entry').append( template(context) );
});