0

I was wondering if it were possible to send an AJAX Post over to a controller contained within a custom module I have created. The reason for doing this is because I want to separate my logic out from the module-sales module.

Alternatively, would it be possible to contain the controller within Magento_Sales as currently my folder structure for this just contains overridden frontend files such as layout / template etc. Any help appreciated on this, cheers

4

1 Answer 1

0

It is possible to create a controller and return a Json from it that you can process on success.

An example :

JS file

 var responseajax = $.ajax({
                    url: action,
                    data: formData,
                    dataType: 'json'
                });

Note that you can build an url with the urlBuilder :

Include the urlbuilder like this :

define(
    [
        'jquery',
        'mage/url',
    ],
    function ($, url) {
... 
                var url= url.build('path/to/controller');
...

Your controller will need to return a json

....
    public function __construct(
        Context $context,
        JsonFactory $jsonFactory,
        Data $jsonHelper,
    )
    {
....
        $this->_jsonFactory = $jsonFactory;
        $this->_jsonHelper = $jsonHelper;
        parent::__construct(
            $context
        );
    }

public function execute(){
$arraydata = your array data
        return $this->_jsonFactory->create()->setJsonData($this->_jsonHelper->jsonEncode($arraydata ));

}

And after that just process the data with your JS

...
responseajax.success(function (response) {
...
response is your json array or Object
....
}
...

This answer is based on the fact that you know how to create a basic route and controller.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.