Home > database >  Use a function from the main file inside a AJAX loaded file
Use a function from the main file inside a AJAX loaded file

Time:04-04

I have this code which is publishing HTML content inside #reviewsList div on page load.

<script>
    $(document).ready(function() {

         function showReviews(page = 1) {

               $.get(URL).done(function (reviews) {
                        
                        $("#reviewsList").html(reviews.html).ready(function() {
                               
                            // DECLARING SOME JS FUNCTIONS THAT ARE USED INSIDE THE LOADED FILE   

                        });

               });

         }

    });
</script>

But the problem is that I have a pagination that is working with inline onclick event - showReviews(page)

Example:
<span onclick="showReviews(3)"></span>

⬆ this is inside the AJAX loaded file

showReviews() is declared in the main file but also used inside the loaded file and I'm getting showReviews() is not a function inside the browser console when click on a pagination page span.

How can I let showReviews() be usable in the AJAX loaded file in this case?

I tried to declare the same function inside the

$("#reviewsList").html(reviews.html).ready(function() {
         
});

but without success.

CodePudding user response:

The problem is because the showReviews() function is declared inside the document.ready handler, so is out of scope on an inline onclick attribute, which requires functions to be declared at global scope.

The quick fix to the problem is to move the showReviews() function declaration outside of document.ready.

The best fix is to remove the reliance on the inline event attribute and to bind your event handlers in JS. The code for that would involve changing the HTML you receive in the AJAX request to something like this:

<span data-review-page="3"></span>

Then using a delegated event handler in the JS:

jQuery($ => {
  function showReviews(page = 1) {
    $.get(URL).done(function(reviews) {
      $("#reviewsList").html(reviews.html);
    });
  }
  
  showReviews(); // on page load
  
  $('#reviewsList').on('click', 'span', e => {
    let page = $(e.target).data('review-page');
    showReviewS(page); // when a span is clicked
  }); 
});

Also note that the ready() event is redundant on anything except the document element. It can be removed from #reviewsList. You state there that you use it to declare some functions based on the new content - again, use delegated event handlers for that, not repeating the same function definitions.

  • Related