How to Enable Ajax Newsletter in Magento 2
Customers subscribe to the newsletter in your store for many reasons such as to understand your product, to get discounts, to educate themselves or even by accident! Yes! It happens!! But they may find it irritating to wait for the page to be refreshed and then continue their activity on the page when they subscribe to the newsletter.
To avoid page reloading and to give the output of successful subscription message, admin can enable Ajax Newsletter in Magento 2 store! It will use the Ajax technology for newsletter subscription and allow customers to subscribe to newsletter without a page refresh.
Here, I’ll show how you can improve the user experience of your store by enabling Ajax Newsletter in Magento 2.
Steps to Enable AJAX Newsletter in Magento 2:
- create di.xml at Vendor\Extension\etc folder
1234567<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"><type name="Magento\Newsletter\Controller\Subscriber\NewAction"><plugin name="Newsletter_Subscriber_NewAction"type="Vendor\Extension\Controller\Plugin\Subscriber\NewAction" sortOrder="10" disabled="false" /></type></config> - create NewAction.php at Vendor\Extension\Controller\Plugin\Subscriber folder
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102<?php/****/namespace Vendor\Extension\Controller\Plugin\Subscriber;use Magento\Customer\Api\AccountManagementInterface as CustomerAccountManagement;use Magento\Customer\Model\Session;use Magento\Customer\Model\Url as CustomerUrl;use Magento\Framework\App\Action\Context;use Magento\Store\Model\StoreManagerInterface;use Magento\Newsletter\Model\SubscriberFactory;/*** Class NewAction*/class NewAction extends \Magento\Newsletter\Controller\Subscriber\NewAction{/*** @var CustomerAccountManagement*/protected $customerAccountManagement;protected $resultJsonFactory;/*** Initialize dependencies.** @param Context $context* @param SubscriberFactory $subscriberFactory* @param Session $customerSession* @param StoreManagerInterface $storeManager* @param CustomerUrl $customerUrl* @param CustomerAccountManagement $customerAccountManagement*/public function __construct(Context $context,SubscriberFactory $subscriberFactory,Session $customerSession,StoreManagerInterface $storeManager,CustomerUrl $customerUrl,CustomerAccountManagement $customerAccountManagement,\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory){$this->customerAccountManagement = $customerAccountManagement;$this->resultJsonFactory = $resultJsonFactory;parent::__construct($context,$subscriberFactory,$customerSession,$storeManager,$customerUrl,$customerAccountManagement);}/*** Retrieve available Order fields list** @return array*/public function aroundExecute($subject, $procede){$response = [];if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {$email = (string)$this->getRequest()->getPost('email');try {$this->validateEmailFormat($email);$this->validateGuestSubscription();$this->validateEmailAvailable($email);$status = $this->_subscriberFactory->create()->subscribe($email);if ($status == \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE) {$response = ['status' => 'OK','msg' => 'The confirmation request has been sent.',];} else {$response = ['status' => 'OK','msg' => 'Thank you for your subscription.',];}} catch (\Magento\Framework\Exception\LocalizedException $e) {$response = ['status' => 'ERROR','msg' => __('There was a problem with the subscription: %1', $e->getMessage()),];} catch (\Exception $e) {$response = ['status' => 'ERROR','msg' => __('Something went wrong with the subscription.'),];}}return $this->resultJsonFactory->create()->setData($response);}} - In your newsletter.phtml file, add below code.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475<div class="block newsletter"><div class="title"><strong>Newsletter </strong></div><div class="content"><form class="form subscribe"novalidateaction="<?php /* @escapeNotVerified */ echo $block->getFormActionUrl() ?>"method="post"data-mage-init='{"validation": {"errorClass": "mage-error"}}'id="newsletter-validate-detail"><div class="field newsletter"><label class="label" for="newsletter"><span><?php /* @escapeNotVerified */ echo __('Sign Up for Our Newsletter:') ?></span></label><div class="control"><input name="email" type="email" id="newsletter"placeholder="<?php /* @escapeNotVerified */ echo __('Enter your email address') ?>"data-validate="{required:true, 'validate-email':true}"/></div></div><div class="actions"><button class="action subscribe primary" title="<?php /* @escapeNotVerified */ echo __('Subscribe sad') ?>" type="submit"><span><?php /* @escapeNotVerified */ echo __('Subscribe') ?></span></button></div><div class="scg-msg"><div class="messages"></div></div></form></div></div><script>require(['jquery'],function($){var form = $('#newsletter-validate-detail');form.submit(function(e) {if(form.validation('isValid')){var email = $("#newsletter-validate-detail #newsletter").val();var url = form.attr('action');var loadingMessage = $('#loading-message');if(loadingMessage.length == 0) {form.find('.input-group').append('<div id="loading-message" style="display:none;padding-top:10px;color: red;font-size: 13px;"> </div>');var loadingMessage = $('#loading-message');}e.preventDefault();try{loadingMessage.html('Submitting...').show();$('.scg-msg > messages').html();$.ajax({url: url,dataType: 'json',type: 'POST',data: {email: email},success: function (data){if(data.status != "ERROR"){$("#newsletter-validate-detail #newsletter").val('');$('#newsletter-validate-detail .scg-msg > .messages').html('<div class="message-success success message" ><div >' +data.msg + '</div></div>');}else{$('#newsletter-validate-detail .scg-msg > .messages').html('<div class="message-error error message" >' +'<div>'+data.msg +'</div></div>');}loadingMessage.html(data.msg);},});} catch (e){loadingMessage.html(e.message);}}});})</script>
Follow the above steps and you’ll get a fully functional Ajax Newsletter in Magento 2 store so that your valuable customers would not have to wait for the page reload!
If you want to show the newsletter subscription status in the Magento 2 customer grid, you can check out: How to Add Newsletter Subscription Column to Customer Grid in Magento 2
I’d be happy to solve your doubts regarding the topic. Feel free to mention them in the comments section below.
Flash 5 stars if the post is helpful to you ?
Thanks!
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
4 Comments
Hello sanjay
i have folllow the given steps but its not working properly in magento 2.4.0 version
its called below error
1 exception(s):
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Ashok\AjaxNewsletter\Controller\Plugin\Subscriber\NewAction\Interceptor, Too few arguments to function Magento\Newsletter\Controller\Subscriber\NewAction::__construct(), 6 passed in /var/www/html/newelastic/app/code/Ashok/AjaxNewsletter/Controller/Plugin/Subscriber/NewAction.php on line 48 and at least 7 expected
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Ashok\AjaxNewsletter\Controller\Plugin\Subscriber\NewAction\Interceptor, Too few arguments to function Magento\Newsletter\Controller\Subscriber\NewAction::__construct(), 6 passed in /var/www/html/newelastic/app/code/Ashok/AjaxNewsletter/Controller/Plugin/Subscriber/NewAction.php on line 48 and at least 7 expected
Hello Ashok,
You need to pass seven argument in parent constructor
https://d.pr/bplwWA
Thank You
Unable to get where to fix code Follow the same step and got error
Too few arguments to function Magento\Newsletter\Controller\Subscriber\NewAction::__construct(), 6 passed in /var/www/html/newelastic/app/code/Custom /AjaxNewsletter/Controller/Plugin/Subscriber/NewAction.php on line 48 and at least 7 expected
Please Provide whole detail where to Update the code
Hello Priya,
You need to pass the same parameter available in the file Magento\Newsletter\Controller\Subscriber\NewAction
Thank You