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

Asked

Viewed 508 times

3

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

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

I wanted to know:

  • What is the difference between checking methods wantsJson() and ajax()?
  • 1

    ajax allows another content-type than JSON?

  • 1

    @Jeffersonquesado is exactly the answer I want to be given. A lot of people who use Laravel think they’re the same.

  • 1

    @Jeffersonquesado ajax uses any type passed in accepts, ie can work with text, xml, json and "binaries"

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 method wantsJson checks if the header accept holds the value application/json. This means that the application is saying, through the header, that it accepts a response like application/json.

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

Already the method ajax is intended to verify that the request is a Xml Http Request, that is, if it was done through Ajax.

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

In the specific case of those who use Angularjs on the front end, I would strongly recommend using wantJson(), because angular always sends this header accept on each request.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.