I need to retrieve some information from my custom admin controller using AJAX.
But when AJAX is used I get current page's entire HTML !
I simply want to get some JSON
data from my custom controller. That I will implement later on.
I'm calling my custom controller from a block in this
URL .../admin/admin/order_shipment/new/order_id/...
Here is my ajax call
var param = 'form_key='+window.FORM_KEY;
$.ajax({
showLoader: true,
url: "admin/PostaPlus/PostaPlusShipping/HSCodes",
data: param,
type: "POST",
// dataType: 'json'
}).done(function (data) {
alert(data);
console.log(data);
});
Here is my custom controller codes,
<?php
namespace PostaPlus\PostaPlusShipping\Controller\Adminhtml;
use Magento\Backend\App\Action;
class HSCodes extends \Magento\Backend\App\Action
{
protected $resultJsonFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
)
{
parent::__construct($context);
$this->resultFactory = $resultJsonFactory;
}
public function execute()
{
//return $this->resultJsonFactory->create()->setData(['a' => 'b']);
return 'test string';
}
public function indexAction(){
//echo 'test string';
}
}
Here is my route file,
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin_hs_codes">
<route id="PostaPlus" frontName="PostaPlus">
<module name="PostaPlus_PostaPlusShipping"/>
</route>
</router>
</config>
Best Answer
I had tried all of the above methods but non of them are working or incomplete so I had decided to answer it in details: Following will be module minimal diagram
1)
2)
3) Need to declare admin router
4)
Now Client Part which is actually bit tricky I am calling it in js file like somefilename.js
gpImageTagSaveUrl
is globel variable which will hold your modules url you can declare it in some js file like followingI had used catalog_product_edit.xml file because I want it at product edit location you can add it in your required file or in default.xml if required on all.
Now in js.phtml declare action url like following: