0

My js file:

function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + "=")) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

$('.cBox').on('click', function(){
    let id_task = $(this).attr('id')
    const data = {
        "id": id_task,
    }
    $.ajax({
        url: "",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({"payload":data}),
        headers: {
            "X-Requested-With": "XMLHttpRequest",
            "X-CSRFToken": getCookie('csrftoken')
        },
        cache: false,
        success: (data) => {
            if (data.status == 1) {
                $(".tasks-list").load(window.location.pathname + " .tasks-list")
            }
        }
    })
});

So, this code listens click on element.
If click was listened - script send AJAX POST request to backend.
If request was successful - backend returns status code 0 or 1.
Then script gets json file from backend and if status code = 1:
script reload div element with class tasks-list

But there is a problem.
div reloads only once, further times it's not reloading. How to fix it?

Sorry for my bad knowlegde of Jquery, Ajax
I'm backender, and my frontend knowledge is minimal

SM1L3_B0T
  • 35
  • 1
  • 6
  • 1
    `$(".tasks-list").load(window.location.pathname + " .tasks-list")` will create a `.tasks-list` div nested inside the old `.tasks-list` div. This is probably not what you want. You probably want to replace the div with it, not load into it. This might be related to the problem. – Barmar Sep 21 '22 at 16:18
  • Is `.cBox` inside `.tasks-list`? If so, you're wiping out any event listeners in that when you reload it. You need to use event delegation, see https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Sep 21 '22 at 16:19
  • @Barmar I want to update data in DIV, but how I understood that my code after ```status:``` isn't corectly – SM1L3_B0T Sep 21 '22 at 16:23
  • @Barmar Yes, it's inside ```.tasks-list``` – SM1L3_B0T Sep 21 '22 at 16:24

1 Answers1

0

You need to replace the div instead of loading into it. So the success: function should be:

        success: (data) => {
            if (data.status == 1) {
                $.get(window.location, function(html) {
                    $(".tasks-list").replaceWith($(html).find(".tasks-list"));
                });
            }
        }

You also need to use event delegation for the event handler, since you're replacing the element that you bound the handler to.

$("#tasks-container").on("click", ".cBox", function() {
    // rest of your code
});

Replace #tasks-container with a selector for the containing element that isn't replaced dynamically, e.g. the parent of .tasks-list.

See Event binding on dynamically created elements?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • how to specify current url and current html tag in ```get``` like in ```load``` method? Because ```get``` method doen't see that i specified html tag – SM1L3_B0T Sep 21 '22 at 17:06
  • I thought `$.get` allowed document fragments in the URL like `$.load`, but I was wrong. I updated the answer to show how to extract it with `$.get`. But this design seems misguided. You should fix the API so it returns the tasks list directly, instead of requiring you to fetch the whole page again. – Barmar Sep 21 '22 at 17:13