Home > other >  Ajax works only once after success post request
Ajax works only once after success post request

Time:09-22

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

CodePudding user response:

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?

  • Related