1

Is it possible to load data from the server using an HTTP POST request within a Magento Module js file?

File located in app/code/MyVendor/myCustomModule/view/frontend/web/js/mycustom.js

Example request:

   function test(){
      $.post("sample_data.php", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
      });
    };

On the frontend I get 403 error when the sample_data.php is called

1

sure: First of all create a new route to be called from your js:

app/code/Vendor/Module/etc/frontend/routes.xml

<?xml version="1.0" encoding="UTF-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="myroute" frontName="myroute">
            <module name="VENDOR_Module"/>
        </route>
    </router>
</config>

Than create your controller: app/code/Vendor/Module/Controller/Ajax/GetData.php - you can call it as you want

<?php
declare(strict_types=1);

namespace Vendor\Module\Controller\Ajax;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\JsonFactory;


/**
 * Class GetData
 *
 * @package Vendor\Module\Controller\Ajax
 */
class GetData extends Action
{

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

    /**
     * GetData constructor.
     *
     * @param \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory
     * @param \Magento\Framework\App\Action\Context $context
     */
    public function __construct(
        JsonFactory $jsonResultFactory,
        Context $context
    ) {
        parent::__construct($context);
        $this->jsonResultFactory = $jsonResultFactory;
    }

    /**
     * Execute action based on request and return result
     *
     * Note: Request will be added as operation argument in future
     *
     * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface
     */
    public function execute()
    {
        $result = $this->jsonResultFactory->create();
        $searchTerm = $this->getRequest()->getParam('some_data'); //if you need data passed from js

        $data = [
            'data1' => 'something',
            'data2' => 'Hello',
            'data3' => 'World'
        ];

        return $result->setData($data);
    }    
}

finally jour js file:


define([
    'jquery',
    'mage/url'
], function ($, url) {
    'use strict';

    var AjaxHelper = function () {};
    AjaxHelper.prototype = {

        /**
         * @param someData string
         * @param setData function
         */
        getData: function (someData, setData) {
            $.ajax({
                url: url.build('myroute/ajax/getdata/'), //myroute is declared in routes.xml, than ajax is the directory and getdata the class 
                data: {
                    some_data: someData
                },
                type: "post",
                error: function () {
                    console.error('Something went wrong');
                },
                success: function (data) {
                    setData(data);
                }
            });
        }
    };
    return new AjaxHelper();
});

Now you can use your js helper wherever you need :)

define([
    'Vendor_Module/js/ajax-helper',
    'ko'
], function (AjaxHelper) {
    'use strict';

    return Component.extend({
        initObservable: function () {
            this._super();
            this.ajaxData = ko.observable();
            return this;
        },

        /**
         * @param data
         * @param event
         */
        getData: function(data, event){
            var self = this;
            AjaxHelper.getDada('somedata', function (data) {
                self.ajaxData(data);
            });
        }
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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