How to Pass Variable from PHTML to JS in Magento 2

javascriptmagento2parameterphtmlrequirejs

I am trying to pass variable to js but it is not working.

My phtml code is like this-

<script type="text/x-magento-init">
    {
        ".open-modal-form": {
            "Vendor_Mod/js/modal-form": {
                "formUrl": "<?php echo $block->getFormAction() ?>"
            }
        }
    }
</script>

My js code is like this –

define(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {

            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                title: 'Ask A Question',
                buttons: [{
                    text: $.mage.__('Submit Question'),
                    class: '',
                    click: function () {
                        var form_data = $("#popup-modal").serialize();


                        $.ajax({
                            url: options.formUrl,
                            type: 'POST',
                            data : form_data,
                            success: function(data){                                
                                console.log(data);                        
                            },
                            error: function(result){
                                console.log('no response !');
                            }
                        });

                        this.closeModal();
                    }
                }],
                /**
                 * Escape key press handler,
                 * close modal window
                 */
                escapeKey: function () {
                    if (this.options.isOpen && this.modal.find(document.activeElement).length ||
                        this.options.isOpen && this.modal[0] === document.activeElement) {
                        this.closeModal();
                    }
                }
            };
            var popup = modal(options, $('#popup-modal'));
            $(".open-modal-form").on('click',function(){ 
                $("#popup-modal").modal("openModal");
            });

        }
    );

I have tried – options.formUrl, and this.options.formUrl. If I use require nothing works, but if I use define the code works but only within the function as shared here – How to pass variable to external js in magento 2

Can someone help. I am basically trying to submit the form using Ajax, but in different JS file. I don't want to code the js within the phtml file.

Best Answer

Below is the code which was functional -

define(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {  
            'use strict';
            $.widget('vendor.mod', {
                options: {
                    submitUrl: '',
                },                                        
                _create: function() {
                    this._initElement();
                },
                _initElement: function() {
                    var that = this;
                    var options = {
                        type: 'popup',
                        responsive: true,
                        innerScroll: true,
                        title: 'Ask A Question',
                        buttons: [{
                            text: $.mage.__('Submit Question'),
                            class: '',
                            click: function () {
                                var form_data = $("#popup-modal").serialize();
                                console.log(that.options.formUrl);
                                return false;                        
                                $.ajax({
                                    url: options.formUrl,
                                    type: 'POST',
                                    data : form_data,
                                    success: function(data){                                
                                        console.log(data);
                                        console.log("sdfss");
                                    },
                                    error: function(result){
                                        console.log('no response !');
                                    }
                                });
                                this.closeModal();
                            }
                        }],
                        /**
                         * Escape key press handler,
                         * close modal window
                         */
                        escapeKey: function () {
                            if (this.options.isOpen && this.modal.find(document.activeElement).length ||
                                this.options.isOpen && this.modal[0] === document.activeElement) {
                                this.closeModal();
                            }
                        }
                    };
                    var popup = modal(options, $('#popup-modal'));
                    $(".open-modal-form").on('click',function(){ 
                        $("#popup-modal").modal("openModal");
                    });
                }
            });
            return $.vendor.mod;
        }
);

The changes made by me were -

1) Created widget and named it as - vendor.mod

2) Used the _create function in which I called my code using _initElement function

3) within _initElement I used var that = this; to use the options variables

4) return $.vendor.mod; to end after all functions

5) console.log(that.options.formUrl); is the line which you can use to check the difference