Search code examples
jqueryarraysajaxwordpressget

Using an array with Ajax GET URL to step though one at a time with each button click


I'm trying to use Ajax GET URL to get the post content of three WordPress posts on the same domain. I have a single button and the URLs in an array in the script and it works, but all three URLs are loaded in a row quickly, I wanted to get each URL one at a time after each click and cycle through, so four clicks start at the beginning of the array again. This is my code:

<button type="button" class="loadAjax">Get Content</button>
<div id="target"></div>

<script>
    (function ($) { 
$('.loadAjax').click(function(){
var url = ['a-nice-post', 'a-small-gallery', 'a-nice-entry']
for (var i = 0; i < url.length; i++) {
      var link = url[i];
    $.ajax({
        url: link,
             type:'GET',
     success: function(data) {  
        $('#target').html($(data).find('.entry-content').html());
     }
  });
}
});
})(jQuery);
</script>

Here is a link to my example when you click the "Get Content" button you will note that the beginning text of the content shows the URL, the rest is Lorem ipsum filler. Also note that it is slow to load the content so wait for a few seconds after clicking the button, I plan to add some feedback for the user after clicking, but I just wanted to keep the code here simple.


Solution

  • but all three URLs are loaded in a row quickly

    That's because you're going through all of them using a for loop, each time the button is clicked -- it's supposed to happen.

    You could modify your code to access the next url from an array by incrementing the index every time the button is clicked, and resetting it to 0 when the index is larger than the number of indexes in the array (array length - 1).

    Example code:

    (function ($) {
        let url = ['a-nice-post', 'a-small-gallery', 'a-nice-entry'];
        let i = 0;
        $('.loadAjax').click(function () {
            const link = url[i];
    
            // increment index unless it is greater than total available indexes
            // in which case, reset it back to 0
            // we use a ternary statement here
    
            i = i === url.length - 1 ? 0 : ++i;
    
            $.ajax({
                url: link,
                type: 'GET',
                success: function (data) {
                    $('#target').html($(data).find('.entry-content').html());
                },
            });
        });
    })(jQuery);