cancel
Showing results for 
Search instead for 
Did you mean: 

Show "Contact Us" form in modal with Ajax submit?

SOLVED

Show "Contact Us" form in modal with Ajax submit?

I need to show the default contact form in a modal and then submit the form using Ajax then show the contents of a static block in the modal to display a "thank you" message. I believe when I'm going wrong is in my controller. This is what I have:

 

 

<?php

namespace AdamGreenwell\ContactUs\Controller\Index;

use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\PhpEnvironment\Request;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Magento\Framework\UrlFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Customer\Model\Session\Interceptor;

class Ajaxcontact extends \Magento\Contact\Controller\Index
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var Context
     */
    private $context;

    /**
     * @var MailInterface
     */
    private $mail;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var \Magento\Framework\Json\Helper\Data $helper
     */
    protected $helper;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var \Magento\Framework\Controller\Result\RawFactory
     */

    protected $resultRawFactory;
    /**
     * @param Context $context
     * @param ConfigInterface $contactsConfig
     * @param MailInterface $mail
     * @param DataPersistorInterface $dataPersistor
     * @param LoggerInterface $logger
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
     */
    public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        LoggerInterface $logger = null,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        UrlFactory $urlFactory
    ) {
        parent::__construct($context, $contactsConfig);
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->resultRawFactory = $resultRawFactory;
        $this->configInterface = $contactsConfig;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
        $this->urlModel = $urlFactory->create();
    }

    /**
     * Post user question
     *
     * @return Redirect
     */

    public function execute() {

        if (!$this->isPostRequest()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $this->sendEmail($this->validatedParams());
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        return $this->_view->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('contact_submission_successful')->toHtml();
    }

    /**
     * @param array $post Post data from contact form
     * @return void
     */

    private function sendEmail($post)
    {
        $this->mail->send(
            $post['email'],
            ['data' => new DataObject($post)]
        );
    }

    /**
     * @return bool
     */
    private function isPostRequest()
    {
        /** @var Request $request */
        $request = $this->getRequest();
        return !empty($request->getPostValue());
    }

    /**
     * @return array
     * @throws \Exception
     */
    private function validatedParams()
    {
        $request = $this->getRequest();
        if (trim($request->getParam('firstname')) === '') {
            throw new LocalizedException(__('First name is missing'));
        }
        if (trim($request->getParam('lastname')) === '') {
            throw new LocalizedException(__('Last name is missing'));
        }
        if (trim($request->getParam('comment')) === '') {
            throw new LocalizedException(__('Message is missing'));
        }
        if (false === \strpos($request->getParam('email'), '@')) {
            throw new LocalizedException(__('Invalid email address'));
        }
        if (trim($request->getParam('hideit')) !== '') {
            throw new \Exception();
        }
        return $request->getParams();
    }
}

This is how I am sending the request:

<script>
    require([
        'jquery',
        'mage/mage'
    ], function ($) {
        var dataForm = $('#contact-form');
        dataForm.mage('validation', {});

        $('.contact-submit').on('click', function () {
            if (dataForm.validation('isValid')) {
                var formData = new FormData();
                $.ajax({
                    url: '<?php echo $this->getUrl('contactus/index/ajaxcontact'); ?>',
                    data: formData,
                    processData: false,
                    contentType: "application/json",
                    showLoader: true,
                    type: 'POST',
                    dataType: 'json',
                    success: function (response) {
                        if (!response.errors) {
                            if (response.redirectUrl) {
                                location.href = response.redirectUrl;
                            }
                        } else {
                            $(' .contact-us .messages .message div').text(response.message);
                            $(' .contact-us .messages .message').show();
                            setTimeout(function () {
                                $('.contact-us .messages .message').hide();
                            }, 5000);
                        }
                    }
                });
                return false;
            }
        })
    });
</script>

But it's not working. Where am I going wrong?

 

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Show "Contact Us" form in modal with Ajax submit?

Try this

 

<p><a href="javascript&colon;void(0)" class="open-contact-form">Open Contact Form</a></p>

<div id="popup-modal">
	<div class="contact-form-popup" style="display: none;">
		<?php echo $this->getLayout()
			->createBlock("Magento\Contact\Block\ContactForm")
			->setTemplate("Magento_Contact::form.phtml")
			->toHtml(); ?>
	</div>
	<div class="static-block-message" style="display: none;">
		<?php echo $this->getLayout()
        		->createBlock('Magento\Cms\Block\Block')
        		->setBlockId('your_block_identifier')
        		->toHtml(); ?>
	</div>
</div>

<script>
require(
    [
        'jquery',
        'Magento_Ui/js/modal/modal'
    ],
    function($, modal) {
    	jQuery(document).ready(function(){
    		var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                title: 'Contact Form',
                buttons: [{
                    text: $.mage.__('Close'),
                    class: '',
                    click: function () {
                        this.closeModal();
                    }
                }]
            };
    		var openModal = modal(options, $('#popup-modal'));

    		jQuery('body').on('click', '.open-contact-form', function(){
    			jQuery('.contact-form-popup').show();
        		jQuery('.static-block-message').hide();
        		jQuery('#popup-modal').modal('openModal');
    		});

    		jQuery('body').on('click', '#contact-form .action.submit', function(e){
    			e.preventDefault();
    			e.stopImmediatePropagation();
        		jQuery.ajax({
        			type: 'post',
        			url: '<?php echo $block->getUrl("contact/index/post") ?>',
        			data: jQuery('#contact-form').serialize(),
        			cache: false,
        			showLoader: 'true',
        			success: function(response) {
        				alert('success');
        				jQuery('.contact-form-popup').hide();
        				jQuery('.static-block-message').show();
        			}
        		});
        		return false;
    		});
    	});
    }
);
</script>

 

If you find my answer useful, Please click Kudos & Accept as Solution.

View solution in original post

2 REPLIES 2

Re: Show "Contact Us" form in modal with Ajax submit?

Try this

 

<p><a href="javascript&colon;void(0)" class="open-contact-form">Open Contact Form</a></p>

<div id="popup-modal">
	<div class="contact-form-popup" style="display: none;">
		<?php echo $this->getLayout()
			->createBlock("Magento\Contact\Block\ContactForm")
			->setTemplate("Magento_Contact::form.phtml")
			->toHtml(); ?>
	</div>
	<div class="static-block-message" style="display: none;">
		<?php echo $this->getLayout()
        		->createBlock('Magento\Cms\Block\Block')
        		->setBlockId('your_block_identifier')
        		->toHtml(); ?>
	</div>
</div>

<script>
require(
    [
        'jquery',
        'Magento_Ui/js/modal/modal'
    ],
    function($, modal) {
    	jQuery(document).ready(function(){
    		var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                title: 'Contact Form',
                buttons: [{
                    text: $.mage.__('Close'),
                    class: '',
                    click: function () {
                        this.closeModal();
                    }
                }]
            };
    		var openModal = modal(options, $('#popup-modal'));

    		jQuery('body').on('click', '.open-contact-form', function(){
    			jQuery('.contact-form-popup').show();
        		jQuery('.static-block-message').hide();
        		jQuery('#popup-modal').modal('openModal');
    		});

    		jQuery('body').on('click', '#contact-form .action.submit', function(e){
    			e.preventDefault();
    			e.stopImmediatePropagation();
        		jQuery.ajax({
        			type: 'post',
        			url: '<?php echo $block->getUrl("contact/index/post") ?>',
        			data: jQuery('#contact-form').serialize(),
        			cache: false,
        			showLoader: 'true',
        			success: function(response) {
        				alert('success');
        				jQuery('.contact-form-popup').hide();
        				jQuery('.static-block-message').show();
        			}
        		});
        		return false;
    		});
    	});
    }
);
</script>

 

If you find my answer useful, Please click Kudos & Accept as Solution.

Re: Show "Contact Us" form in modal with Ajax submit?

Wonderful! Thank you very much!

 

I was making the whole process much harder than it had to be. Thank you again, that helped tremendously.