I'm trying to transform my Jquery code into a function to make it more dynamic. As parameters I want to pass the ID of the Handlebars SCRIPT tag, the ID of the DIV tag where the result will be printed, the query URL for AJAX and the PARAMETERS for Ajax.
I was doing some tests only with the parameters (URL and Parameters) but I did not get any results (apparently it's a question of the asynchronous method but it was not very clear to me).
This is the original and functional code:
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var context = $.post("http://localhost/api/api.php", {a: 'foo', b: 'bar'});
context
.then((response) => {
var parsejson = JSON.parse(response);
$("#content-placeholder").html(template({objects:parsejson}));
});
And this is my proposal for a function to simplify the previous code:
function testing (id, target, url, parameters){
var source = document.getElementById(id).innerHTML;
var template = Handlebars.compile(source);
var context = $.post(url, parameters);
context
.then((response) => {
var parsejson = JSON.parse(response);
return $(target).html(template({objects:parsejson}));
});
};
var cool = testing("test-template", "#test-placeholder", "http://localhost/api/api.php", {a: 'foo', b: 'bar'});
console.log(cool);
But I'm getting an "undefined" on the console.