0

Is it possible to call a frontend javascript function from a plugin php file? The js function should be executed in the browser.

view/frontend/web/js/send.js

function send() {
    console.log("Sending here...")
}

Plugin/plg.php

public function afterAddProduct(Cart $subject, $result, $productInfo, $requestInfo = null)
{
    echo '<script>console.log("in plugin");send();</script>';
}

This is what I'm trying to do. The send function is available in the browser and I'm able to manually trigger it from browser console.

But I'm unable to get the javascript in the .php plugin file working in the browser. Even console.log("in plugin") is not working.

Is there a way to execute clientside javascript from .php plugin file?

1 Answer 1

0

Since Magento is using an MVC (Model View Controller) architecture, returning pure HTML (or Javascript) code in your plugin won't work.

Depending on what you really want to achieve, it might be better to do an Ajax call in the frontend to grab data from the server (or run some custom logic doing something on the server-side) and work with the data returned by the Ajax call. If you need the server-side to "drive" the execution flow, you need to render the data in the respective template and then run some Javascript logic when the passed data has a certain state set.

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.