operat Posted May 29, 2019 Posted May 29, 2019 I have a "Data" page, whose template file does not contain any HTML markup, as it only collects several data, prepares it as JSON and returns it like this: return json_encode($data); It generally works, which is fine obviously. However, when I access the page address in the browser, I can see the JSON text – which is the expected, but not the wanted behaviour. Is there a way to return the JSON only, when the page is requested with AJAX and redirect it, when accessed directly? I'm aware of $config->ajax. For some reason, however, it's never 'true', hence doesn't have any helpful effect here. Any thoughts or advice? Thank you!
Zeka Posted May 29, 2019 Posted May 29, 2019 if($config->ajax) { header('Content-Type: application/json'); echo $json; $this->halt(); // like die(); } else throw new Wire404Exception(); 5
Robin S Posted May 29, 2019 Posted May 29, 2019 8 hours ago, operat said: I'm aware of $config->ajax. For some reason, however, it's never 'true', hence doesn't have any helpful effect here. See how PW determines $config->ajax here. So you may need to set the X-Requested-With header: 2
operat Posted May 31, 2019 Author Posted May 31, 2019 On 5/29/2019 at 11:40 PM, Robin S said: So you may need to set the X-Requested-With header @Robin S Setting the header in the vanilla JS XMLHttpRequest solved the actual problem. $config->ajax works as expected, now. Thank you! On 5/29/2019 at 3:27 PM, Zeka said: header('Content-Type: application/json'); echo $json; @Zeka A quite useful hint, which helped to improve the code. Thanks! 1
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now