I have seen several examples where JSON is returned from a custom controller. I have tried many different ways and every time my controller always returns HTML. I do not know why it does not work.
My Controller:
namespace Test\Module\Controller\Index;
use Magento\Framework\App\Action\Context; use Magento\Framework\Controller\ResultFactory;
class Test extends \Magento\Framework\App\Action\Action {
/* @var \Magento\Framework\Controller\Result\JsonFactory */
private $resultJsonFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory ) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory; }
public function execute() {
$response['status'] = "SUCCESS";
$resultJson = $this->resultJsonFactory->create();
$resultJson->setData($response); // array value set in Json Result Data set
return $resultJson; // return json object
} }
I am calling the controller with Ajax. My Ajax request:
function ajaxRequest() {
try {
jQuery.ajax({
url: 'my-controller-url',
dataType: "json",
type: "POST",
data: data.cart })
.done(function( json ) {
if (json.status === "SUCCESS") {
toggleConfirmOverlay();
progress[data.currentSection].className = 'done';
displayPopupCart();
} else {
alert( "Sorry, there was a problem!" );
console.log(json.error);
}
})
.fail(function( xhr, status, errorThrown) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
.always(function( xhr, status ) { // toggleSpinner();
});
} catch (e) {
console.log('error: ' + e);
} }
In the JS console I receive an error that JSON cannot be decoded. Inspecting the result shows a full HTML page with navigation.