cancel
Showing results for 
Search instead for 
Did you mean: 

Call Block Function using Knockout js in magento 2

Call Block Function using Knockout js in magento 2

I need to call a function, that is written in block, but I need to call on every time the page loads.

Problem:

What Issue I am facing now is, I can call a function written in the block, but it was called only once, after refreshing the page or reloading, the same function was not called. Anyone has an idea, if so , please share it.

How do we achieve this via Knockout js or any other method?

2 REPLIES 2

Re: Call Block Function using Knockout js in magento 2

To call a block function using Knockout.js in Magento 2, you need to follow these steps:

  1. Create a Custom Block:

    • Define a custom block in your module or theme.
    • Add the necessary function in this block.
  2. Expose Block Function to JavaScript:

    • Use a custom controller or layout XML to pass the block data to the frontend.
    • Ensure the block's output is accessible by Knockout.js.
  3. Use Knockout.js to Bind Data:

    • Bind the block data to your Knockout.js view model.
    • Utilize Knockout.js to dynamically update the UI based on the block's function.

Step-by-Step Example

Step 1: Create a Custom Block

Re: Call Block Function using Knockout js in magento 2

@jabbarkhan872c 

 

Hey,

 

You can add the phtml file using the block and, in that phtml file you can do JS ajax code and, in controller you can call block method Alternate option that is in knockout js. you can add the ajax and call controller.

 

Thank You!

Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.