0

On AJAX I want to display the Buy Now button. For that, I created one variable

 var buy_now_button = '<span title="<?php echo __('Buy Now') ?>" id="buy-now" class="action buynow primary" data-mage-init='{ "Test_Detail/js/buy-now": { "form": "#product_addtocart_form"  }}'><span><?php echo __('Buy Now') ?></span></span>';

Because of data-mage-init, the function is not working.

3
  • Do you get any errors?
    – Ben Crook
    Commented Sep 13, 2017 at 12:26
  • @BenCrook function does not get called
    – jassi
    Commented Sep 13, 2017 at 12:32
  • @BenCrook Uncaught SyntaxError: Unexpected token {
    – jassi
    Commented Sep 13, 2017 at 12:33

1 Answer 1

1

It looks like the single quote needs escaping, but according to this answer you can't simply use \ to escape the quote either (I'd still give it a try if I was you).

You can use &apos; to escape it though, whilst it is not very easy to read what is happening it may solve the problem for you.

Cleaner Method

The cleanest way to do this would be to use the x-magento-init method, and then you can pass the PHP through to the JS file.

Usage for that method is along these lines:

PHTML

<script type="text/x-magento-init">
    {
        "*": {
            "yourJsAliasOrPathHere": {
                "buyNowButton": "<?php echo ... ?>"
            }
        }
    }
</script>

JS

define([
    'jquery'
], function ($) {
    'use strict';

    return function(config) {
        alert(config.buyNowButton);
    }
});
3
  • <script type="text/x-magento-init"> { "*": { "Test_Detail/js/buy-now"": { "#buy-now": "<?php echo ... ?>" } } } </script>
    – jassi
    Commented Sep 13, 2017 at 12:54
  • I have tried above, can u pls explain little more briefly
    – jassi
    Commented Sep 13, 2017 at 12:55
  • You'll need to replace ... with whatever you want to echo, and escape the quotes in there to. What this does is pass the PHP through to the JS file. I don't have time to explain in detail sorry, the below links should help though. If not then try the method you did before and just escape the quotes. devdocs.magento.com/guides/v2.1/javascript-dev-guide/javascript/… and magento.stackexchange.com/questions/89187/… are the links.
    – Ben Crook
    Commented Sep 13, 2017 at 12:58

Your Answer

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

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