XF 2.0 Detect ajax request

Lukas W.

Well-known member
Is there a globally accessible way to determine if the incoming request is ajax (the page will return json) or not? I need to access this information from within the BB Code renderer to alter the output accordingly.
 
There isn't something that is a 100% guarantee how the page is going to be returned, though there are hints in the request object -- it may be easiest to look at how an ajax request looks compared to a regular one to see what you want to use. _xfResponseType might be sufficient.

That said, that approach feels like bad news to me. It certainly makes me wonder if there's a better approach.
 
That said, that approach feels like bad news to me. It certainly makes me wonder if there's a better approach.

It's kind of a trade-off approach. I'm enabling users to use google webfonts in their forum posts. When rendering the page it's fairly easy to send the required fonts to the templater, bundle them and attach them to the head of the page, but it isn't that simple if you're for example editing one of these posts and add a new font. That font also needs to be loaded, but you can't just append it to the head without javascript, cause you're in the ajax process. So instead of trying to somehow jiggle it to the page head and opening tons of vulnerabilities like I did with my last version in XF1, I'm just appending the link-tag in place to load the required font. In that situation it would be possible that the browser loads the font multiple times (if the user uses the font multiple times), but it's really just a temporary workaround as this issue resolves itself on the next page load.

I've btw used this code to detect whether the answer will be ajax/json or not:
Code:
/** @var \XF\Http\Response $response */
$response = \XF::app()->container('response');
if($response->contentType() === 'application/json') {
    // Ajax, do stuff here.
}
else {
    // Non-ajax.
}
Seems to be accurate enough to work.
 
Back
Top Bottom