0

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.

2
  • Which part of the code are you trying to decode the response? Dec 18, 2019 at 22:50
  • I thought that my question was clear and straight forward but no replies. Doesn't seem like this is a good place to get questions answered.
    – Kyle Waid
    Dec 26, 2019 at 17:38

1 Answer 1

0

The issue was because I was not understanding the routes feature properly. In this module I declared 2 routes. One for the view and one for the add to cart. I was using the same url and expecting the add to cart to work when I needed to go to url/cart.

I forgot that when using the url it will default to Index.php. I had a file Cart.php in the same directory so I should have gone to url/cart

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.