Jump to content
operat

Page behaviour when returning JSON

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!

Share this post


Link to post
Share on other sites
if($config->ajax) {
	header('Content-Type: application/json');
	echo $json;
	$this->halt(); // like die();
} else throw new Wire404Exception();

 

  • Like 5

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...