Need to Initialization js after ajax response magento 2
I have the same issue and I resolved it by calling catalogAddToCart after the ajax call.
Here is the code snippet
$.ajax({
dataType: 'html',
type: 'GET',
url:url,
success: function(data){
var data = $($.parseHTML(data));
var productList = data.find('.products.list').html();
productWrapper.append(productList);
// this solved the problem
$( "form[data-role='tocart-form']" ).catalogAddToCart();
},
});
I have resolved this issue using below code:
htmlObject=jQuery("#custom_search_autocomplete").html(result);
htmlObject.find('[data-role=autocompletesearch-tocart-form], .form.map.checkout').attr('data-mage-init', JSON.stringify({'catalogAddToCart': {}}));
htmlObject.trigger('contentUpdated');
From the accepted answer I made this generic solution which is a bit easier to understand:
$(document).ajaxComplete(function() {
$('[data-mage-init]').each(function() {
var mageInit = $(this).attr('data-mage-init');
if (typeof mageInit !== 'undefined') {
var script = document.createElement("script");
script.type = "text/x-magento-init";
script.text = '{"*":' + mageInit.trim() + '}';
$(this)[0].appendChild(script);
$(this).trigger('contentUpdated');
$(this).removeAttr('data-mage-init');
}
});
});