0

I am getting email address in the database with this function:

protected $subscriberFactory;

    public function __construct(
    \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
    ...code...
    )
    {
     $this->subscriberFactory= $subscriberFactory;
     ....code....
    }

public function subscribeNewsLetter($email)
     {

        $this->subscriberFactory->create()->subscribe($email);

     }

In my template file, calling it as:

<table>
 <tr>
  <td>
   <input type="checkbox" onClick="<?php $block- 
>subscribeNewsLetter($email); ?>">Subscribe to News Letter</button>r<br>
   <script>
      function subscribeNewsLetter($email)
          {
            alert("subscribeNewsLetter");
          }
  </script>
 </td>
</tr>
</table>

The problem here is, when I refresh the page function subscrieNewsLetter() is executed before checking the checkbox. Even checkbox is not checked, the email address gets stored in database.

I find some examples for this using AJAX like: https://blog.mdnsolutions.com/magento-2-newsletter-subscription-via-ajax/ but it is bit different form my problem. I know magetions will find a more smarter way to do it.

0

I found the solution by following this aproach:

https://blog.qaisarsatti.com/magento_2/magento-2-jquery-ajax-request/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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