I want to call an ajax function on a button click. All other things are working fine. But I can't read the parameter which is passed to the js. How can I do it? Here is my code.
Phtml file
<div>
<div id="successmsg" class="success message" style="display:none">Success</div>
<input type="text" id="name" class="name" maxlength="8" placeholder="<?= $block->escapeHtml(__('ENTER NAME')) ?>">
<input type="button" value="<?= $block->escapeHtml(__('CHECK')) ?>" id="check-button">
</div>
<script type="text/x-magento-init">
{
"#check-button": {
"Company_Module/js/check": {"ajaxurl":"<?php echo $block->escapeHtml($block->getCheckUrl())?>"}
}
}
</script>
JS File
require([
"jquery",
'mage/template',
"mage/mage"
], function (,ドル mageTemplate, alert){
$('#check-button').click(function(){
jQuery("#successmsg").css('display','none');
$.ajax({
url: config.ajaxurl,
type: 'POST',
dataType: 'json',
data: {name: $('#name').val()},
complete: function(response) {
if (response.responseJSON.success) {
jQuery("#successmsg").attr('style','display: block');
},
});
});
});
2 Answers 2
Your Js module should return function, to obtain configuration from .phtml; And also register your requireJs module by using define([], function(){});
So should be like:
define([
"jquery",
'mage/template',
"mage/mage"
], function (,ドル mageTemplate, alert){
return function(config) {
$('#check-button').click(function(){
jQuery("#successmsg").css('display','none');
$.ajax({
url: config.ajaxurl,
type: 'POST',
dataType: 'json',
data: {name: $('#name').val()},
complete: function(response) {
if (response.responseJSON.success) {
jQuery("#successmsg").attr('style', 'display: block');
}
}
});
});
};
});
You can pass data from phtml template file to your custom Javascript module using either data-mage-init or x-magento-init, the only rule is that your JS module has to return a function, in order to have access to the config object:
Using data-mage-init :
<div id="unique" data-mage-init='{
"Vendor_Module/js/model/fact-check": {
"factProducts": <?= /* @noEscape */ $viewModel->getFactList() ?>,
"currentFact": "<?= /* @noEscape */ $currentFact ?>"
}}'> </div>
Using x-magento-init :
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"fact-checker": {
"component": "Vendor_Module/js/model/fact-check",
"factProducts": <?= /* @noEscape */ $viewModel->getFactList() ?>,
"currentFact": "<?= /* @noEscape */ $currentFact ?>"
}
}
}
}
}
</script>
In your custom JS module :
define([
'jquery'
], function($) {
return function(config, element) {
'use strict';
const factProducts = config.factProducts;
const currentFact = config.currentFact;
// Your custom logic here
}
});
Keep in mind that if you use a ui component with the data-bind="scope: 'fact-checker'" binding, the JS errors will be silent and not show up in console.
Explore related questions
See similar questions with these tags.