Sallar Rabiei
Sallar Rabiei

Reputation: 782

How jQuery only apply once?

I use the following lines to add a picture before, a span. I use $( document ).ajaxComplete(function() { to load this section after ajax finished.

$(document).ajaxComplete(function() {
  $(document).ready(function() {

    $("#filter-id-1886 > span.text-title").before("<img width='35px' src='https://example.com/wp-content/themes/rasa/assets/img/01.png' alt='cheese icon' class='mr-2'>");

  });

});

My problem is that it adds a picture after few seconds. In fact, after 5 minutes, I see over 10 images added before the span, I am looking for a solution to add picture only once.

Update (to add more information): I use ajax to load data from the database, and in this case, if I remove $( document ).ajaxComplete(function() the picture will not add before span. In fact, I am looking for a solution that: Only apply function after ajax complete once. I thought about using delay but, I am looking for a more stable solution.

Upvotes: 0

Views: 91

Answers (1)

Alexander Nied
Alexander Nied

Reputation: 13668

$(document).ajaxComplete fires the callback "whenever an Ajax request completes". So, if you wrap your ajax event in an ajaxComplete inside of a $(document).ready what will happen is:

  1. Once the document is ready, your AJAX request fires
  2. Once it completes, the callback to the AJAX complete is called again, which will execute automatically because the document is already ready, sooooo
  3. ...another AJAX request will be fired.
  4. Return to step 2

You have an infinite loop. In order to avoid this, and not knowing anything else about your setup, I'd recommend simply removing the wrapping ajaxComplete:

$(document).ready(function() {
  $("#filter-id-1886 > span.text-title").before("<img width='35px' src='https://example.com/wp-content/themes/rasa/assets/img/01.png' alt='cheese icon' class='mr-2'>");
});

Upvotes: 1

Related Questions