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

0

I use the Guzzle\Http library to be able to make requests to some urls with PHP.

I'm doing webservice with our systems, where, if the request is recognized as Ajax , the returned result is Json . Otherwise, HTML is returned.

However, I now need to make requests in those urls with Guzzle , and I want the request to be made by Guzzle , so I'm also returned in Json .

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

Do I need to put some or some headers to work?

    
asked by anonymous 22.04.2016 / 20:57

1 answer

1

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

X-Requested-With: XMLHttpRequest

It does not mean that it is Ajax, it actually means that it is XmlHttpRequest (as explained here Ajax is not a language So what is it? )

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

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

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

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

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

Or using Guzzle\Http like this:

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

$client->request('GET', '/caminho/foo/bar/baz', [
    'headers' => ['X-Requested-With' => 'XMLHttpRequest']
]);
Just an additional framework, such as Laravel and cakephp, use these methods to detect if it has the header GuzzleHttp\Client :

  • Laravel:

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

    if ($this->request->is('ajax')) {
    
22.04.2016 / 21:05