PageController can't be requested via XmlHttpRequest in Shopware 6
Asked Answered
T

1

8

I am trying to send a request to my custom StorefrontController on the latest Shopware 6.2.2 but I am getting the following error:

PageController can't be requested via XmlHttpRequest.

I am doing a regular httpClient request as such from a custom JS plugin :


export default class MyCustomPlugin extends Plugin {

  static options = {
      dataUrl: '', // comes from the twig as "path('frontend.path.to.route')"
      product: null,
      params: {},
      loadingIndicatorClass: 'is-loading',
      responseSelector: 'some-selector-class'

  }

  init () {
      // this.el.innerHTML = LoadingIndicator.getTemplate()
      this.httpClient = new HttpClient()
      const query = querystring.stringify(this.options.product)
      this.sendDataRequest(query)
  }

  /**
   * Add classes to add loading styling.
   * Prevents the user from clicking filter labels during filter request.
   */
  addLoadingIndicatorClass () {
      this.el.classList.add(this.options.loadingIndicatorClass)
  }

  /**
   * Remove loading styling classes.
   */
  removeLoadingIndicatorClass () {
      this.el.classList.remove(this.options.loadingIndicatorClass)
  }

  /**
   * Send request to get filtered product data.
   *
   * @param {String} filterParams - active filters as querystring
   */
  sendDataRequest (filterParams) {

      this.addLoadingIndicatorClass()

      this.httpClient.abort()
      this.httpClient.get(`${this.options.dataUrl}?${filterParams}`, (response) => {
          this.renderResponse(response)
          this.removeLoadingIndicatorClass()
      })
  }

  /**
   * Inject the HTML of the response to the element.
   *
   * @param {String} response - HTML response
   */
  renderResponse (response) {
      ElementReplaceHelper.replaceFromMarkup(response, this.options.responseSelector, false)
      window.PluginManager.initializePlugins()
  }
}

And here is my StorefrontController route:

    /**
     * @Route("/path/to_route", name="frontend.path.to.route", methods={"GET"})
     */
    public function someAction(Request $request, Context $context): JsonResponse

Can anyone tell me why the request is not going? I want to send a simple AJAX request to my own controller in Shopware 6.

Thanks!

Teyde answered 24/6, 2020 at 14:28 Comment(0)
G
7

Try with adding:

defaults={"XmlHttpRequest"=true} to your Route.

So after the changes you will have:

/**
* @Route("/path/to_route", name="frontend.path.to.route", methods={"GET"}, defaults={"XmlHttpRequest"=true})
*/

Also make sure that the scope is properly defined in the controller using the @RouteScope annotation. Since your code is a storefront JavaScript plugin, it should have the storefront scope defined.

Gaiter answered 25/6, 2020 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.