How to make requests with Http Guzzle pretending to be "AJAX"?

Asked

Viewed 789 times

0

I usually use the libraryGuzzle\Http to be able to request some urls with PHP.

I’m webserving with our systems, where, if the request is recognized as Ajax, the returned result is Json. Otherwise it is returned HTML.

However, I now need to requisition these urls with the Guzzle, and I want that when the requisition is made by Guzzle, also be returned to me the answer in Json.

How to make requests with the library Guzzle\Http, as if it were AJAX run by a browser?

I need to put some headers or some headers to make it work?

  • 1

    The person who gave the negative could offer information on what could be improved in the question.

1 answer

1


In fact there is no way to detect if it is real ajax (and this is what helps us), what we do is a send a header which uses the prefix x-, generally in HTTP the use of this prefix means experimental.

A use case of this is jQuery, for example I create a simple GET request with XmlHttpRequest with nothing I won’t have to detect, so jQuery sends this header:

X-Requested-With: XMLHttpRequest

Doesn’t mean it’s Ajax, it actually means it’s XMLHttpRequest (as explained here Ajax is not a programming language. So what is?)

In case we detect if the shipment is XMLHttpRequest, in the Guzzle\Http you can define in the instance of Guzzle\Http, to "inherit" the settings in other requests. Thus, you simplify the configuration:

  $client = new Guzzle\Http(['headers' => ['X-Request-With' => 'XMLHttpRequest']]);

  $client->put(/** **/);

  $client->post(/** **/);

  $client->get(/** **/);

Or using the GuzzleHttp\Client thus:

$client = new GuzzleHttp\Client(...);

$client->request('GET', '/caminho/foo/bar/baz', [
    'headers' => ['X-Requested-With' => 'XMLHttpRequest']
]);

Just an additional one, frameworks like Laravel and cakephp use these methods to detect if it has the header X-Requested-With' => 'XMLHttpRequest:

  • Laravel:

    public function index(Request $request)
    {
        if($request->ajax()){
    
  • cakephp:

    if ($this->request->is('ajax')) {
    
  • 1

    The Symfony then, according to his opinion, did right. There the method called $request->isXMLHttpRequest(). I believe that the $request->isAjax() came to "simplify the bike".

  • 1

    @Wallacemaxters in my framework is just Request::is('xhr') :)

Browser other questions tagged

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