7

I want to pass $vendor_city to knockoutJS:

<?php
    $vendor_city = $vendor->getData('city');
?>

<div id="m2-component" data-bind="scope:'ko'">
<script type="text/x-magento-init">
    {
        "#m2-component": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "ko": {
                        "component": "some_mdl/js/estimate",
                        "template" : "some_mdl/estimate"
                    } // How do I pass a variable here to estimate.js?
                }
            }
        }
    }
    </script>
</div>

estimate.js

define(['uiComponent', 'ko', 'jquery'], function (Component, ko, jquery) {

    return Component.extend({
        initialize: function (config) {
            var self = this;
            this._super();

            // I want get that variable here

        },
});

I already done like this:

<script>
    window.sellerlocation= '<?=$vendor_city;?>';
</script>

But I want to pass a PHP variable to KnockoutJS via a KnockoutJS component initialize, not a JavaScript window object.

0

1 Answer 1

8

Try the below code:

<?php
    $vendor_city = $vendor->getData('city');
?>

<div id="m2-component" data-bind="scope:'ko'">
<script type="text/x-magento-init">
    {
        "#m2-component": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "ko": {
                        "component": "some_mdl/js/estimate",
                        "template" : "some_mdl/estimate",
                        "vendorCity": <?= /* @escapeNotVerified */ $vendor_city ?>
                    }
                }
            }
        }
    }
    </script>
</div>

estimate.js

define(['uiComponent', 'ko', 'jquery'], function (Component, ko, jquery) {

    return Component.extend({
        initialize: function (config) {
            var self = this;
            this._super();
            console.log(config.vendorCity);
        },
});

Make sure that $vendor_city data is in encode format.

Refresh your JavaScript code, clean the cache, and check the output in the console.

8
  • It give me error, Cannot read property '*' of undefined section-config.js:33 Oct 31, 2018 at 6:28
  • where you use *? Oct 31, 2018 at 6:40
  • nowhere, It give this error on "vendorCity": <?= /* @escapeNotVerified */ $vendor_city ?> when I remove this line, error gone. Oct 31, 2018 at 6:42
  • 1
    you need to use quotes like "<?= /* @escapeNotVerified */ $vendor_city ?>" Oct 31, 2018 at 6:46
  • thanks @RohanHapani +1 for you answer. please update it according my last comment. Oct 31, 2018 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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