1

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');                 
           },

        });            
    });
});
3

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');
                  }
               }
            });
        });
    };
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.