Undrium
Undrium

Reputation: 2678

Jquery Ajax call works with HTML but not JSON

I have started to work with Drupal 8 and doing ajax calls to the server using the fresh controller system implemented by the Drupal team.

My problem occurs now when I have defined the route and I make an ajax call using jquery. If I set the dataType to "json" I receive a 404, but changing it to "html" will work.

The function my route points to looks like this:

function createResponse(){
    return new JsonResponse(['data' => 'test']);
}

My response/request-headers look like this:

Response

Cache-Control   must-revalidate, no-cache, post-check=0, pre-check=0, private
Connection  keep-alive
Content-Encoding    gzip
Content-Language    en
Content-Type    application/json
Date    Wed, 19 Nov 2014 12:20:35 GMT
Expires Sun, 19 Nov 1978 05:00:00 GMT
Keep-Alive  timeout=10
Server  nginx
Transfer-Encoding   chunked
Vary    Accept-Encoding
X-Powered-By    PHP/5.5.18-1~dotdeb.1
X-UA-Compatible IE=edge,chrome=1

Request Header

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  9
Content-Type    application/json; charset=utf-8
Host    d8test.local
Referer http://d8test.local/
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0
X-Requested-With    XMLHttpRequest

Is this Drupal 8 specific? Is there some stupid variable forbidding json xmlhttprequests? I can access the route normally by surfing to the route and I can get the data using html but I really do need it in json-format.

This is the jquery code:

jQuery.ajax({
      url: drupalSettings.path.basePath + "testAjax",
      type: "post",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      data: {'type' : 'list'},
      success: function(data){
          console.log(data);
      }
});

testAjax is the route I have defined, it works fine and this also work if I change the dataType to "html" something that feels very weird.

Upvotes: 0

Views: 1160

Answers (1)

Undrium
Undrium

Reputation: 2678

Thanks to very vital clues from Spokey in the comments I found out the problem, my route was wrongly setup in Drupal. Instead of _controller I used _content. _controller immediately accesses the function without adding lots of markup-overhead.

So if you bump into this problem yourself, make sure your routes.yml file has the _controller setting and not the _content one.

Upvotes: 1

Related Questions