How do I set up an AJAX page?

I have read threads and documentation but can’t figure out how to use AJAX on the PHP side.

  1. What I did was adding a folder called ajax in the content folder, with an empty ajax.txt.
  2. Then I added ajax.php in the site/templates folder with some content.
  3. It works when I go to /ajax

If ajax page

http://getkirby.com/docs/cheatsheet/request/ajax

I added this to ajax.php and it did NOT write AJAX on the page:

if(kirby()->request()->ajax()) { echo 'AJAX'; }

Why not? Is it wrong aproach to add an AJAX page the way I do?

Set 404 on an AJAX page

http://getkirby.com/docs/advanced/options

It says I could add headers with templates and HTTP headers. I tried this in the config.php, where I have a template file called before_ajax.php.

c::set('headers', array('before_ajax', 404) );

It does not seem to run before_ajax at all. It does not seem to add 404 to the page. It still returns 200. Maybe this is the wrong way to force 404 to the AJAX page?

Set error header

http://getkirby.com/docs/toolkit/api/header/error

This functions seems like the right one but where should I put it?

Summer

The easiest way for me would be an example code and some basic instructions. I use Kirby 2 (the latest).

In your ajax.php template, you can put something like this:

<?php
if(kirby()->request()->ajax()) {

//do your ajax stuff here ...
    
}
else {
	header::status('404');
}

So if you call this page directly, you’ll get an empty page and an HTTP error code.

If it is called via your JS script, it should do whatever it is supposed to do.

Let’s do something easy as an example:

<?php
if(kirby()->request()->ajax()) {


    $images = $pages->find('intro')->images()->shuffle();
    $image = $images->first();
    echo $image->url();
    
}
else {
	header::status('404');
}

You might as well redirect to the error page here instead of just sending the error code.

This piece of code just shuffles the images in an intro folder and echoes the first.

Then in the javascript:

function loadBackground() {
   $.ajax({
      url: 'ajax',
      success : function(filename) {        
        $('#intro').css('background-image', 'url('+filename+')');
        }
   });
}
setInterval(loadBackground, 7000); 

The script calls the ajax page and replaces the background image in the #intro div with the one from the ajax template.

1 Like

For testing I made it a little bit simpler. On the ajax.php template I use this:

<?php
if(kirby()->request()->ajax()) {
    echo 'AJAX';
}
else {
	header::status('404');
}

On my page where I use the AJAX function, I use this:

<script>
function test() {
   $.ajax({
      url: 'ajax',
      success : function(response) {        
        console.log(response);
        }
   });
}

setInterval(test, 7000);
</script>

It works like expected. Awesome!