Jump to content

Two Little Frustrations with AJAX


Brian Scramlin
 Share

Recommended Posts

I just wanted to share that I added an AJAX-powered gallery to an artist website that I developed and host: https://jackpinecreations.com/gallery/

3197az.gif.725dd8cdeb146d00f75b5533aac654f6.gif

There were two things that frustrated me about creating this. Perhaps you can show me a better way.

1. After creating my processing script, which I placed under /templates/scripts/get-items.php, I realized that I would get a 403, due to ProcessWire's routing and security. This forced me to have to create a template and page for this little script. This was frustrating simply because it seemed unnecessarily confusing. But worse, see #2.

2. I usually use config.php to prepend and append each of my templates with a head.inc and foot.inc, which keeps my templates easy to use and I don't have to go and use the GUI to do so on each template separately. However, since I realized I needed to create a new template and page so as to access it, whenever I sent POST params to it, I would get the header and footer along with it!!! I could find no workarounds and had to remove the pre/append calls in config.php and use the GUI on each template individually.  

Code Below if you're interested:

HTML and JavaScript (forgive my sad JavaScript skills, I know this can be tightened up)

<!-- Begin Grid -->
<div class="container mt-4">
  <div id="gallery" class="row">
    <?php foreach ($page->children("limit=9") as $child): ?>
      <div class="col-6 col-md-4 gallery-item">
        <a href="<?= $child->url ?>" title="View <?= $child->title ?>">
          <img class="gallery-item" src="<?= $child->item_featured_image->size(640, 640)->url ?>" alt="<?= $child->title ?> Image">
        </a>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<!-- End Grid -->

<div class="center-block text-center">
  <button id="get-more-items" type="button" name="get-more-items" class="btn-vintage">Load More</button>
</div>

<script type="text/javascript">
  var buttonGetItems = document.getElementById("get-more-items");
  var indexStart = 0;

  buttonGetItems.addEventListener("click", function() {
    indexStart += 9;

    $.ajax({
      url: '<?= $pages->get(1186)->url ?>',
      type: "POST",
      dataType:'json', // add json datatype to get json
      data: ({page_id: <?= $page->id ?>, index_start: indexStart}),
      success: function(data){
        console.log(data);
        if (data[1]) {
          //for each element, append it.
          $.each(data, function(key, value) {
            $("#gallery").append(value);
          });
        } else {
          $("#get-more-items").after('<p class="center-block text-center">There are no more items to load.</p>');
          $("#get-more-items").remove();
        }
      }
    });
  });

</script>

Processing Script

<?php

$items_array = [];
$i = 0;

foreach ($pages->get($input->post->page_id)->children->slice($input->post->index_start, 9) as $child) {
  $i++;
  $items_array[$i] =
    "<div class='col-6 col-md-4 gallery-item'>
      <a href='$child->url' title='View $child->title'>
        <img src='{$child->item_featured_image->size(640,640)->url}' alt='$child->title Image'>
      </a>
    </div>";
}

echo json_encode($items_array);

I love ProcessWire for hundreds of reasons, but I've been using AJAX more and more, and I'm not liking having to create templates to access scripts. 

Any advice?

Edited by Brian Scramlin
added GIF so people don't have to go to link if they don't want to.
Link to comment
Share on other sites

11 minutes ago, Brian Scramlin said:

Any advice?

1. If you put your PHP file in the site root it won't be affected by the htaccess restrictions. You could also put it any other place besides those places with restricted access.

2. See the "Files" tab in the template settings: "Disable automatic prepend of file..." / "Disable automatic append of file..."

  • Like 4
Link to comment
Share on other sites

my preferred way is to make a generic 'service' template, and have a 'services' index page, under which you can add as many services/ajax endpoints as you want; then you just have the template include the correct service php file by matching the name; in any given service file, you can do a return $this->halt() or exit() to stop the appending; you can also just turn off prepend/append for that service template and you'd be all set...

1 hour ago, Brian Scramlin said:

I usually use config.php to prepend and append each of my templates with a head.inc and foot.inc,

that's risky and not so future proof; also on some templates it might prevent you from doing some processing before the head loads, for that template – maybe add a dns prefetch to the header, or a custom script or style for that template's pages. if you don't have a lot of templates, it is probably better to just include head and foot in each template file and skip the auto prepend/append.

The benefit of using pages for your endpoints is that you have full native access to the api, and no bootstrapping necessary..

 

  • Like 6
Link to comment
Share on other sites

Thank you, everyone! These are helpful strategies and I will integrate them into my work. What a great community. Regarding the auto-pre/appending, this is documented on the PW (https://processwire.com/docs/tutorials/how-to-structure-your-template-files/) as Direct Output with Automatic Inclusions, but I know Delayed Output and Markup Regions are probably preferred and I will work on switching to those strategies.

  • Like 2
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

×
×
  • Create New...