Jump to content

Page behaviour when returning JSON


operat
 Share

Recommended Posts

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!

Link to comment
Share on other sites

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:

 

  • Like 2
Link to comment
Share on other sites

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!

  • Like 1
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...