Jump to content
Brian Scramlin

Two Little Frustrations with AJAX

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.

Share this post


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

Share this post


Link to post
Share on other sites
2 minutes ago, Brian Scramlin said:

1. Would the file be overwritten when upgrading PW? 

Not so long as you keep it outside of the /wire/ folder.

Share this post


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

Share this post


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

Share this post


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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By horst
      Hi, on a site I want to disable access to original images and only allow to access thumbnails and watermarked image variations.
      EDIT:
      A good solution for protecting original images can be found a bit down in this thread:
       
      Old content of this initial post:
       
    • By Guy Incognito
      I seem to be running into a repeated fatal error in a fresh PW install version 3.0.148. I can't quite put my finger on the pattern but it seems to be around deleting image fields or removing images from certain image fields.
      This is the trace from the log generated by trying to save a page and delete an image from an image field:
      Fatal Error: Uncaught Error: Cannot access protected property Pageimage::$original in /wire/core/PageimageVariations.php:256 Stack trace: 1. /wire/core/Pageimage.php(1327): PageimageVariations->getInfo() 2. /wire/core/Wire.php(386): Pageimage->___isVariation() 3. /wire/core/WireHooks.php(823): Wire->_callMethod() 4. /wire/core/Wire.php(450): WireHooks->runHooks() 5. /wire/core/Pageimage.php(1369): Wire->__call() 6. /wire/core/Pageimage.php(399): Pageimage->getOriginal() 7. /wire/core/WireData.php(333): Pageimage->get() 8. /wire/core/PageimageVariations.php(256): Pro Line 256 of /wire/core/PageimageVariations.php Earlier in the day I was experimenting with custom fields for images for the first time and kept running into this error, thinking it was me using this feature wrong and not having time to read up I deleted the custom image fields template and went about my business. So now I don't know if I triggered an issue or whether it was never related to the custom image fields in the first place?
      Any ideas?
    • By ICF Church
      Hi 👋
      Anyone else having this problem?
      Requirements:
      - Repeater (matrix & normal) with mutlilanguage fields (text, textarea…) 
      - Backend language set to something other than default (ie. German) 
      Reproduce:
      - Add a new repeater Item (ajax, I found no way to possible to disable it with matrix)

      (Notice how the default language tab is active instead of the backend language…)
      - Write something into the (default language) field
      - Try to save, if field is required, this will not work. If not required, then when reloading, the content will be inside the backend language field, instead of the default language field who was (presumably) active
      Analysis:
      When  loading  a new repeater element with ajax, the default langue tab is active, but the backend language inputfield is visible (with no visual indication). When writing into the field, it will populate the backend language. When manually clicking on the default language tab (which is already active), the field will switch to the actual default language field (which is [now] empty) (that can now be populated…)
      Also Notice, the labels of the elements to be added are in default language as well instead of the translated label (images instead of Bilder)…
      ProcessWire 3.0.148, Profields 0.0.5…
      Is it my system configuration, or does anyone else have the same issue? This is a screen recording of the problem:
      Issue: https://github.com/processwire/processwire-issues/issues/1179

      Screen Recording 2020-02-25 at 14.18.31.mov
    • By humanafterall
      I'm using some Custom fields for images: 
      https://processwire.com/blog/posts/pw-3.0.142/#custom-fields-for-files-images

      When I save the page, and return the fields are blank. When I re-add the text to the fields and save again then the fields save as expected.

      I know this is stated as being quite experimental but it's super useful feature I'd love to get working correctly.
      I have fields that are CKEditor fields but have overidden this on the image specific template. I've also tried it with regular text fields and I get the same bug.
      (currently using Processwire 3.0.155)
      **UPDATE**
      I've found this issue is specific to editing on pages using the PageTable fieldtype. The fields are not saving when I save the page in the PageTable.
    • By Robin S
      Displays image tags overlaid on the thumbnail using customisable colours. This makes it easier to see which images have which tags without needing to open the edit pane for individual images or changing to the list view.
      Screenshot

      Usage
      Enable tags for one or more image fields. Install the Image Thumbnail Tags module. Optionally configure colours for any of your tags.
       
      https://github.com/Toutouwai/ImageThumbnailTags
      https://modules.processwire.com/modules/image-thumbnail-tags/
×
×
  • Create New...