conditional knockout with ajax response
-
13-04-2021 - |
Question
I created an default template for items in the minicart. The difference to the default template should be shown only under a specific condition.
<!-- ko if: $parent.myvalueactive(product_sku)==true -->
some stuff
<!-- /ko -->
I added a function in my javascript file, that gets loaded with the minicart:
myvalueactive: function (target) {
console.log(target);
var aktiviert;
$.ajax({
method: "POST",
url: "mymodule/index/active",
data: { q: target},
async: false,
dataType: "json",
success : function(response){
if (response.aktiv=='true') {
aktiviert='true';
};
}
});
if (aktiviert=="true") {
return true;
}
else {
return false;
}
}
This works so far on the product pages and CMS-pages. However, it doesnt work in the checkout process - The content isnt loaded in the minicart on the cart-page nor on the checkout page. Did I mess up ajax or something. Im not even sure, what to search for, for debugging....
Solution
Ok, I figured it out. My mistake was the url in the ajax request. I needed to add a slash in front of the url, to make it work on other pages:
$.ajax({
method: "POST",
url: "/mymodule/index/active", //added a slash in front of the url
data: { q: target},
async: false,
dataType: "json",
success : function(response){
if (response.aktiv=='true') {
aktiviert='true';
};
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange