Magento – Unable to add success message in magento2

ajaxmagento2success-message

Unable to add success message through ajax success function using messageManager in magento2.

How to display default message of magento2 using ajax functionality?

JS code

        $('#finalSubmit').click( function() 
        { //can be replaced with any event
            //dataForm.validation('isValid'); //validates form and returns boolean
            $('.ajax-file-upload > form > input').unwrap(); 

            if(dataForm.validation('isValid') === false)
            {
                $("#mulitplefileuploader").uploadFile(settings);
                return false;
            }


            if(dataForm.validation('isValid')==true)    
            {
                $.ajax({
                    type:'POST',
                    url: '<?php echo $this->getUrl("customdesignsubcategories/index/sendEmail");?>',
                    data: dataForm.serialize(),
                    dataType:'json',
                    success: function(data){

                        if(data.status == "CaptchaError")
                        {
                            $('#customdesignsubcategories_form .invalid-captcha').show();
                            $('#customdesignsubcategories_form').find('input[name*="captcha"]').focus();    
                        }else if(data.status == "Success")
                        {
                            
                        }
                    }
                })
                
            }
        });

Controller code

 public function execute()
{   
    $response = array();
    $resultJson = $this->resultJsonFactory->create();

    $previous_full_url = $this->_redirect->getRefererUrl();
    $page_type = (string)$this->pageType();
    
    $cds_params = array();
    $cds_params = $this->getRequest()->getParams();
    $captcha_formID = $this->_CustomDesignSubCategoriesModel->getCaptchaFormId();
    $_captcha = $this->_customerSession->getData($captcha_formID . '_word');
    $this->_customerSession->setData($page_type, array($cds_params));

    if ($cds_params['captcha'][$captcha_formID] == $_captcha['data']) 
    {
        if((count($cds_params) > 0) && !empty($cds_params['comment']) && !empty($cds_params['name']) && !empty($cds_params['form_email']) )
        {
            $attachment_dir = $this->_CustomDesignSubCategoriesModel->getAttachementSavingDir();
            $file_dir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath() . $attachment_dir;     
            $uploadedFiles = $this->getRequest()->getParam('uploadedfiles');
            $_uploadedFiles = explode(",",str_replace('"','',ltrim($uploadedFiles,",")));
            $filesToAttach = $this->getRequest()->getParam('filesToAttach');
            $result = array();
            $oneDimensionalArray = array();
            if($filesToAttach !="")
            {
                $_filesToAttach = explode(",",rtrim($filesToAttach,","));
                $_uniqueFilesToAttach = array_unique($_filesToAttach);
                foreach($_uniqueFilesToAttach as $key=>$value)
                {
                    if($this->getRequest()->getParam(str_replace(".","_",$value)))
                    {
                        $temp[] = $this->getRequest()->getParam(str_replace(".","_",$value));
                        foreach($temp as $val)
                        {
                            $result[] = $val;
                        }
                        unset($temp);
                    }
                }
            }

            if(sizeof($result) > 0)
            {
                $oneDimensionalArray = call_user_func_array('array_merge', $result);
                $max_file_size = 26214400; //25MB
                $file_size = 0;

                foreach($oneDimensionalArray as $file) 
                {
                    if(file_exists($file_dir.$file) && $file) 
                    {
                        $currentFileSize = filesize($file_dir.$file);
                        $file_size = $file_size + $currentFileSize;
                    }
                }

                if($file_size > $max_file_size) 
                {
                    $arr = array();
                    $arr = $this->getRequest()->getParams();
                    $this->_customerSession->setData('data', array($arr));
                    $this->messageManager->addError('File size exceeded.');
                    $this->_redirect('*/*/');
                    return;
                }

                $allowed_file_type = array("pdf", "ppt", "pptx","doc", "docx", "jpg", "jpeg", "png", "gif", "xlsx", "xlsm", "xlsb", "xls", "xltx", "xltm", "xlt", "csv", "xlam", "xla", "ods", "zip", "txt");
                foreach($oneDimensionalArray as $file)
                {
                    if(file_exists($file_dir.$file) && $file) 
                    {
                        $ext = pathinfo($file_dir.$file, PATHINFO_EXTENSION);
                        $ext = strtolower($ext);
                        if(!in_array($ext, $allowed_file_type)) 
                        {
                            $arr = array();
                            $arr = $this->getRequest()->getParams();
                            $this->_customerSession->setData('data', array($arr));
                            $this->messageManager->addError('This extension is not allowed.');
                            $this->_redirect($previous_full_url);
                            return;
                        }
                    }
                }
            }

            $store = $this->_storeManager->getStore()->getId();
            $emailTemplateVariables = array();
            $emailTemplateVariables = $this->getRequest()->getParams();
            $emailTemplateVariables['emailTitle'] = $this->_CustomDesignSubCategoriesModel->getEmailMessageTitle();
            $emailTemplateVariables['tableTitle'] = $this->_CustomDesignSubCategoriesModel->getTableTitle();
            $emailTemplateVariables['emailSubject'] = $this->_CustomDesignSubCategoriesModel->getEmailSubject();

            $to = $this->_CustomDesignSubCategoriesModel->getEmailReciept();
            $bcc =$this->_CustomDesignSubCategoriesModel->getBccEmailReciept();
            $emails = explode(",",$bcc);

            $headers = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

            try
            {
                $this->_template  = $this->_scopeConfig->getValue(self::XML_PATH_EMAIL_CUSTMDESIGNSUBCATEGORIES,ScopeInterface::SCOPE_STORE,$store);
                $this->_transportBuilder->setTemplateIdentifier($this->_template)
                ->setTemplateOptions(array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $store))
                ->setTemplateVars($emailTemplateVariables)
                ->setFrom(['name' => 'Slideteam','email' => 'design@slideteam.net'])
                ->addTo($to,"Admin");

                if(!empty($emails))
                {
                    foreach($emails as $email)
                    {
                        $this->_transportBuilder->addCc($email);
                    }
                }

                foreach ($oneDimensionalArray as $file)
                {
                    if (file_exists($file_dir.$file))
                    {
                        $this->_transportBuilder->addAttachment(file_get_contents($file_dir.$file),$file);                      
                    }
                }

                $response['status'] = "Success";
                
                $transport = $this->_transportBuilder->getTransport();
                $transport->sendMessage();  
                $this->messageManager->addSuccess('Your query has been successfully submitted.');
                return $resultJson->setData($response);     
                $this->_customerSession->unsetData($page_type);
                $this->_redirect($previous_full_url);


            } 
            catch (\Exception $e) 
            {
                echo $e->getMessage();
                $this->_messageManager->addError("Unable to send email");
                $this->_redirect($previous_full_url);
            }
        }
        else
        {
            $this->messageManager->addError('Please fill up required fields');
            $this->_redirect($previous_full_url);  
        }

    }
    else
    {
        $response['status'] = "CaptchaError";
        $this->_customerSession->setBrCaptchaError(true);

    }
    return $resultJson->setData($response);
}

Best Answer

=> Add this code in your controller :

<?php
namespace VendorName\ModuleName\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Addtocart extends \Magento\Framework\App\Action\Action {

protected $_messageManager;

public function __construct(
    Context $context,
    \Magento\Framework\Message\ManagerInterface $messageManager,
) {
    parent::__construct($context);
    $this->_messageManager = $messageManager;
}

public function execute() {
    // your logic code
    $this->_messageManager->addSuccess('Shopping cart updated succesfully.');
}