{"id":183,"date":"2018-09-17T06:03:02","date_gmt":"2018-09-17T06:03:02","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2018\/09\/17\/enable-ajax-newsletter-in-magento-2\/"},"modified":"2025-05-22T17:19:10","modified_gmt":"2025-05-22T11:49:10","slug":"enable-ajax-newsletter-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/enable-ajax-newsletter-in-magento-2\/","title":{"rendered":"How to Enable Ajax Newsletter in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To avoid page reloading and to give the output of successful subscription message, admin can enable&nbsp;<i><strong>Ajax Newsletter in Magento 2<\/strong><\/i>&nbsp;store! It will use the Ajax technology for newsletter subscription and allow customers to subscribe to newsletter without a page refresh.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here, I\u2019ll show how you can improve the user experience of your store by enabling&nbsp;<i><strong>Ajax Newsletter in Magento 2.<\/strong><\/i><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Steps to Enable AJAX Newsletter in Magento 2:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create di.xml at&nbsp;<strong><strong>Vendor\\Extension\\etc<\/strong><\/strong>&nbsp;folder<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:ObjectManager\/etc\/config.xsd\">\n    &lt;type name=\"Magento\\Newsletter\\Controller\\Subscriber\\NewAction\">\n        &lt;plugin name=\"Newsletter_Subscriber_NewAction\"\n                type=\"Vendor\\Extension\\Controller\\Plugin\\Subscriber\\NewAction\" sortOrder=\"10\" disabled=\"false\" \/>\n    &lt;\/type>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Create&nbsp;<strong>NewAction.php<\/strong>&nbsp;at&nbsp;<strong><strong>Vendor\\Extension\\Controller\\Plugin\\Subscriber<\/strong><\/strong>&nbsp;folder<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\/**\n *\n *\/\n \nnamespace Vendor\\Extension\\Controller\\Plugin\\Subscriber;\n \nuse Magento\\Customer\\Api\\AccountManagementInterface as CustomerAccountManagement;\nuse Magento\\Customer\\Model\\Session;\nuse Magento\\Customer\\Model\\Url as CustomerUrl;\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Store\\Model\\StoreManagerInterface;\nuse Magento\\Newsletter\\Model\\SubscriberFactory;\n \n\/**\n * Class NewAction\n *\/\nclass NewAction extends \\Magento\\Newsletter\\Controller\\Subscriber\\NewAction\n{\n    \/**\n     * @var CustomerAccountManagement\n     *\/\n    protected $customerAccountManagement;\n \n    protected $resultJsonFactory;\n \n    \/**\n     * Initialize dependencies.\n     *\n     * @param Context $context\n     * @param SubscriberFactory $subscriberFactory\n     * @param Session $customerSession\n     * @param StoreManagerInterface $storeManager\n     * @param CustomerUrl $customerUrl\n     * @param CustomerAccountManagement $customerAccountManagement\n     *\/\n    public function __construct(\n        Context $context,\n        SubscriberFactory $subscriberFactory,\n        Session $customerSession,\n        StoreManagerInterface $storeManager,\n        CustomerUrl $customerUrl,\n        CustomerAccountManagement $customerAccountManagement,\n        \\Magento\\Framework\\Controller\\Result\\JsonFactory $resultJsonFactory\n    )\n    {\n        $this->customerAccountManagement = $customerAccountManagement;\n        $this->resultJsonFactory = $resultJsonFactory;\n        parent::__construct(\n            $context,\n            $subscriberFactory,\n            $customerSession,\n            $storeManager,\n            $customerUrl,\n            $customerAccountManagement\n        );\n    }\n \n    \/**\n     * Retrieve available Order fields list\n     *\n     * @return array\n     *\/\n    public function aroundExecute($subject, $procede)\n    {\n        $response = [];\n        if ($this->getRequest()->isPost() &amp;&amp; $this->getRequest()->getPost('email')) {\n            $email = (string)$this->getRequest()->getPost('email');\n \n            try {\n                $this->validateEmailFormat($email);\n                $this->validateGuestSubscription();\n                $this->validateEmailAvailable($email);\n \n                $status = $this->_subscriberFactory->create()->subscribe($email);\n                if ($status == \\Magento\\Newsletter\\Model\\Subscriber::STATUS_NOT_ACTIVE) {\n                    $response = [\n                        'status' => 'OK',\n                        'msg' => 'The confirmation request has been sent.',\n                    ];\n                } else {\n                    $response = [\n                        'status' => 'OK',\n                        'msg' => 'Thank you for your subscription.',\n                    ];\n                }\n            } catch (\\Magento\\Framework\\Exception\\LocalizedException $e) {\n                $response = [\n                    'status' => 'ERROR',\n                    'msg' => __('There was a problem with the subscription: %1', $e->getMessage()),\n                ];\n            } catch (\\Exception $e) {\n                $response = [\n                    'status' => 'ERROR',\n                    'msg' => __('Something went wrong with the subscription.'),\n                ];\n            }\n        }\n \n        return $this->resultJsonFactory->create()->setData($response);\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In your&nbsp;<strong>newsletter.phtml<\/strong>&nbsp;file, add below code<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;div class=\"block newsletter\">\n    &lt;div class=\"title\">&lt;strong>Newsletter &lt;\/strong>&lt;\/div>\n    &lt;div class=\"content\">\n        &lt;form class=\"form subscribe\"\n            novalidate\n            action=\"&lt;?php \/* @escapeNotVerified *\/ echo $block->getFormActionUrl() ?>\"\n            method=\"post\"\n            data-mage-init='{\"validation\": {\"errorClass\": \"mage-error\"}}'\n            id=\"newsletter-validate-detail\">\n            \n            &lt;div class=\"field newsletter\">\n                &lt;label class=\"label\" for=\"newsletter\">&lt;span>&lt;?php \/* @escapeNotVerified *\/ echo __('Sign Up for Our Newsletter:') ?>&lt;\/span>&lt;\/label>\n                &lt;div class=\"control\">\n                    &lt;input name=\"email\" type=\"email\" id=\"newsletter\"\n                                placeholder=\"&lt;?php \/* @escapeNotVerified *\/ echo __('Enter your email address') ?>\"\n                                data-validate=\"{required:true, 'validate-email':true}\"\/>\n                &lt;\/div>\n            &lt;\/div>\n            &lt;div class=\"actions\">\n                &lt;button class=\"action subscribe primary\" title=\"&lt;?php \/* @escapeNotVerified *\/ echo __('Subscribe sad') ?>\" type=\"submit\">\n                    &lt;span>&lt;?php \/* @escapeNotVerified *\/ echo __('Subscribe') ?>&lt;\/span>\n                &lt;\/button>\n            &lt;\/div>\n            &lt;div class=\"scg-msg\">\n                &lt;div class=\"messages\">\n                &lt;\/div>\n            &lt;\/div>\n        &lt;\/form>\n    &lt;\/div>\n&lt;\/div>\n \n \n&lt;script>\n    require(['jquery'],function($){\n        var form = $('#newsletter-validate-detail');\n        form.submit(function(e) {\n            if(form.validation('isValid')){\n                var email = $(\"#newsletter-validate-detail #newsletter\").val();\n                var url = form.attr('action');\n                var loadingMessage = $('#loading-message');\n \n                if(loadingMessage.length == 0) {\n                    form.find('.input-group').append('&lt;div id=\"loading-message\" style=\"display:none;padding-top:10px;color: red;font-size: 13px;\">&amp;nbsp;&lt;\/div>');\n                    var loadingMessage = $('#loading-message');\n                }\n \n                e.preventDefault();\n                try{\n                    loadingMessage.html('Submitting...').show();\n                    $('.scg-msg > messages').html();\n \n                    $.ajax({\n                        url: url,\n                        dataType: 'json',\n                        type: 'POST',\n                        data: {email: email},\n                        success: function (data){\n                            if(data.status != \"ERROR\"){\n                                $(\"#newsletter-validate-detail #newsletter\").val('');\n                                $('#newsletter-validate-detail .scg-msg > .messages').html('&lt;div class=\"message-success success message\" >&lt;div >' +\n                                    data.msg + '&lt;\/div>&lt;\/div>');\n                            }else{\n                                $('#newsletter-validate-detail .scg-msg > .messages').html('&lt;div class=\"message-error error message\" >' +\n                                    '&lt;div>'+data.msg +'&lt;\/div>&lt;\/div>');\n                            }\n                            loadingMessage.html(data.msg);\n                        },\n                    });\n                } catch (e){\n                    loadingMessage.html(e.message);\n                }\n            }\n        });\n    })\n&lt;\/script><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Follow the above steps and you\u2019ll get a fully functional&nbsp;<em>Ajax Newsletter in Magento 2<\/em>&nbsp;store so that your valuable customers would not have to wait for the page reload!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to show the&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/manage-newsletter-subscriptions-in-magento-2\/\">newsletter subscription<\/a>&nbsp;status in the Magento 2 customer grid, you can check out:&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/add-newsletter-subscription-column-to-customer-grid-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Add Newsletter Subscription Column to Customer Grid in Magento 2<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-183","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/183","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=183"}],"version-history":[{"count":5,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/183\/revisions"}],"predecessor-version":[{"id":15597,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/183\/revisions\/15597"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=183"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=183"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=183"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}