Dominykas55 Dominykas55 - 6 months ago 60
Ajax Question

JS, jQuery not working when I refresh part of page with Ajax

So i have some JS files included in my page that are simple for displaying blocks on click ant etc..

On other part of page I have a button. When I click it an ajax call is made that returns some values that I display in page. To display it im reloading part of page like this:

$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});


This reloads part of page, displays values and etc...

However, after ajax call is made, the JS is not working anymore.. I can click my buttons and nothing happens, no errors or anything..

I think its about ajax, that I refresh part of twig and it messes up the previously loaded JS files.. But what can I do in that situation? Somehow refresh the loaded JS files? How?

Answer

As said @Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :

function init() {
    $(document).on('click', '.yourclass', function (e) {
     //your content
    }

     // add every button who needs to be reloaded.
}

Init them on loading page first :

$("document").ready(function() {
init();
})

And on success of Ajax call :

$.ajax({
    type: 'POST',
    url: 'add',
    dataType: 'JSON',
    data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
    success: function (data) {
      if(data.success == false){
       alert('error')
      }else{
        $('.test').load(" .test");
        $('.sidebar').load(" .sidebar");
        $('.top').load(" .top");
        init();
       }
    }
});