ques-yYy43o1h

Search A2Z 24

Question : Need to Initialization js after ajax response magento 2

I am working on ajax concept to load product but when i got response below script not initialize

<script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {}
            }
        }

</script>

Can anyone help me to initialize script after response.

asked March 9, 2017

3 Answers

Dispalying 1 to 3 of 3 |

Best Answer : After ajax load or after DOM ready

require([
	'jquery',
	'mage/mage',
	'Magento_Catalog/product/view/validation',
	'Magento_Catalog/js/catalog-add-to-cart'
], function ($) {
	var currentF = $('form[data-role="tocart-form"]');
	currentF.attr('data-mage-init', JSON.stringify({'catalogAddToCart': {}}));	
	var mageInit = currentF.attr('data-mage-init');
	if (typeof mageInit !== 'undefined') {
		$(currentF).catalogAddToCart();
		currentF.removeAttr('data-mage-init');
	}								   
});		
See comments (0) | Comment
Answered 4 Months ago

From the accepted answer I made this generic solution which is a bit easier to understand:

	element.find("[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");
		}
	});
See comments (0) | Comment
Answered 4 Months ago

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");
See comments (0) | Comment
Answered 4 Months ago
Dispalying 1 to 3 of 3 |

Write your Answer write code <pre class="brush: xml">---code---</pre>

Login as a member to access answering block !! click-here
loading...

Reveal Modal Goodness

This is a default modal in all its glory, but any of the styles here can easily be changed in the CSS.

This is just a simple modal with the default styles, but any type of content can live in here. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi quis sem vel enim eleifend tristique. Etiam tincidunt faucibus pharetra.

×