What is the difference between Request :: wantsJson () and Request :: ajax ()?

2

In Laravelle 4, I used to use the Request::ajax() method to know and the request was an XHR.

When I started using Laravel 5, I realized that I was being used more in the tutorials than Request::wantsJson() . However, I noticed that Request::ajax() still exists in Laravel 5.

I wanted to know:

  • What is the difference between the check methods wantsJson() and ajax() ?
asked by anonymous 13.07.2018 / 17:41

1 answer

3

Well, let's look at the source code of both?

WantsJson:

public function wantsJson()
{
    $acceptable = $this->getAcceptableContentTypes();

    return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}

Ajax:

public function ajax()
{
    return $this->isXmlHttpRequest();
}

The wantsJson method checks whether the accept header has the application/json value. This means that the application is saying, through the header, that it accepts a response of type application/json .

The name of the method itself, translated, is something like: "Do you want JSON?".

The ajax method is to check if the request is an Xml Http Request , that is, if it was done through Ajax.

Note that an ajax request can be returned in HTML, XML, JSON, among other things.

In the specific case of someone who uses AngularJS on the front end, I would strongly recommend using wantJson() , since angular always sends this header accept on each request.

    
13.07.2018 / 17:46