0

Im trying to create an Ajax call in frontend but I get redirect to Homepage when I get to the controller. Can anyone explain why? Many thanks. Here my script in phtml

<script type="text/javascript">
require(["jquery"],function($) {
    $(document).ready(function() {
        var customurl = "<?php echo $block->escapeUrl($block->getUrl('webentry/index/search'))?>";
        $("#search-button").on('click', function () {
          $.ajax({
            url: customurl,
            type: 'POST',
            dataType: 'json',
            data: {
              postCode: $('#headquarter_post_code').val()
          },
          success: function(response) {
            console.log("Success!!");
          },
          error: function (xhr, status, errorThrown) {
            console.log(errorThrown);
          }
        });
      });
    });
});

My controller

class Search extends \Magento\Framework\App\Action\Action {
protected $resultFactory;
public function __construct (
    \Magento\Framework\App\Action\Context $context,
    ResultFactory $resultFactory
) {
    $this->resultFactory = $resultFactory;
    parent::__construct($context);
}

public function execute()
{
    $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

    $response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
    $response->setHeader('Content-type', 'text/plain');
    $country = 'india';
    $state = 'gujarat';
    $response->setContents(
        $this->_jsonHelper->jsonEncode(
            [
                'default_country' => $country,
                'state' => $state,
            ]
        )
    );
    return $response;
}

}

1 Answer 1

0

in your ajax request

var param = { 
    replyComment : replyComment.value()
};
$.ajax({
    showLoader: true,
    url: replyControllerURL,
    data: { data: param} ,
    type: "POST",
    dataType: 'json'
}).done(function (data) {
    console.log(data.success)
});

In your controller

use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;    
class Reply extends \Magento\Backend\App\Action
{
    public function __construct(
        Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->resultJsonFactory    = $resultJsonFactory;
        parent::__construct($context);
    }


    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        if ($this->getRequest()->isAjax()) 
        {
            $params = $this->getRequest()->getParam('data'); 
            
                try{
                    $response =[
                        'status' => true,
                        'message' => __('Reply Has Been Send And recorded Successfully'),
                    ];
                }catch(Exception $ex){
                    $response =[
                        'status' => false,
                        'message' => __('Something went wrong'),
                    ];
                }
            return $result->setData($response);
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.