Kirby Routes and Ajax

Hey All,

Im having a problem with kirby routes where it doesn’t seem to send a response.

This is my Route code in my config file:

c::set('routes', array(
	array(
		'pattern' => 'save-page',
		'action'  => function() {
			
			return 'saved';
			
		},
		'method' => 'ALL'
	)
));

And then my javascript is:

xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '/save-page');
xhr.send(payload);

onStateChange just lets me know wether it works or not. I tested it with just a plain save.php file which just returned ‘saved’ which worked fine.

Update: The status error returned is 500

Cheers guys

First, if the status code is 500 you probably have something helpful in your error log. What does it say?

Secondly, you’re returning a string (saved) from your route. Do you have a page called ‘saved’? If not then you won’t get the response you expect. You need to make a response object instead. This probably isn’t the cause of you 500 status, though.

Thanks for your reply.

I don’t have a page named ‘saved’ but at this stage that is purely there to provide a response.

The error i get is:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

But clicking on the page it clearly works as i can echo 'working' and it displays.

Thanks

Edit: Changing return to true gives a 200 response, can you explain why that is?

Returning a string simply does not work. You can either echo and stop execution or use the following code:

c::set('routes', array(
	array(
		'pattern' => 'save-page',
		'action'  => function() {
			
			return new Response('saved', 'txt');
			
		},
		'method' => 'ALL'
	)
));

I know this is a little pedantic, but that’s not quite true. If the string returned is a page that exists, then it’ll work fine. The problem is that if the page doesn’t exist then kirby::render is passed false instead of a page object as its first variable and that throws an error.

Yes, you are actually right. :smiley:
It does work, but not as expected in this case. Printing arbitrary text by returning it isn’t supported, as (like you say) that’s interpreted as a page UID.

Thanks guys!

I did a bit of reading of the Docs and see where I went wrong now, thanks for the assistance.

All is good now cheers.