Need help with Ajax requests with Kirby

Well, I don’t know if this helps, but this is an example of loading a page in a modal via ajax. You would have to adapt this to your use case:

In the link, I use a data target (the element where the content should go) so that I can use the function for various calls with different targets:

<a class="load" data-target="#modal-container" href="<?php echo $page->url() ?>"><?php echo $page->title()->html()) ?></a>

The template is quite normal, except it loads the header and footer only if it’s not an ajax call. If Javascript is disabled, the content is loaded into a separate page.

<?php if(!kirby()->request()->ajax()) { snippet('header'); snippet('nav-main'); } ?>
	<section class="<?php echo $page->uid(); ?>" id="<?php echo $page->uid(); ?>">
		<div class="section-inner">
			<h1><?php echo $page->title()->html() ?></h1>
			<?php echo $page->text()->kirbytext()?> 
		</div>
	</section>
<?php if(!kirby()->request()->ajax()) { snippet('footer'); } ?>

And the jQuery bit:

  var url = $('.load').data('url');
  var button = $('<button class="btn close" data-url="' + url + '" onclick="closeModal()">x</button>');
  function openUrlInModal(url, target){
    $.ajax({
	url: url,
	success: function(data) {
	$(target).append(data).addClass('modal');
	$('.modal').fadeIn('slow');
	$(target).find('section').append(button);
	}
    });
  }

  $('.load').bind('click', function(e) {
    var target = $(this).data("target");
    e.preventDefault();
    window.scrollTo(0,0);
    openUrlInModal($(this).attr('href'), target);
 });
6 Likes