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?

asked Sep 24, 2021 at 10:39

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.

answered Sep 24, 2021 at 18:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.