slimphp / Slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
http://slimframework.com
MIT License
11.98k stars 1.95k forks source link

isXHR() not working #2295

Closed olignyf closed 7 years ago

olignyf commented 7 years ago

Hi,

Please tell me if it is my usage that is wrong but I think there is something not working as I expected with isXhr(). It always returns false, even on Ajax requests.

In this middleware, I print a header and footer, but only when not XHR. Unfortunately the header is still printed for XHR requests. Any idea what I am doing wrong or if it is a slimphp bug?

Thanks, Francois

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $request, Response $response, callable $next) 
{
    $renderer = $this->get('renderer'); 
    error_log(print_r($request,true));

    // header
    if (!$request->isXhr()) 
    {  $response = $renderer->render($response, 'header.phtml');
    }

    // actual request
    $response = $next($request, $response);

    // footer
    if (!$request->isXhr()) 
    {  $response = $renderer->render($response, 'footer.phtml');
    }

    return $response;
});
tflight commented 7 years ago

Does your ajax request have this header? X-Requested-With: XMLHttpRequest

piotr-cz commented 7 years ago

It's a convention that javascript libraries (jQuery, MooTools) used to set such header to every request

geggleto commented 7 years ago

Yes. I do believe so.

olignyf commented 7 years ago

Yes I was using just a native XMLHttpRequest object. I will add that special header and retest. I thought the browser was responsible to add it. Many thanks.

On Tue, Aug 22, 2017 at 10:35 AM, Glenn Eggleton notifications@github.com wrote:

Yes. I do believe so.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/slimphp/Slim/issues/2295#issuecomment-324046057, or mute the thread https://github.com/notifications/unsubscribe-auth/ABGeBuRYeSSfUbFj7LbKh7HqvHATl4tuks5saudNgaJpZM4O8tHK .

olignyf commented 7 years ago

Thanks, adding X-Requested-With as I did below in my code made it work !

var xhr = new XMLHttpRequest();
xhr.open(type, encodeURI(url));
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
...