简体   繁体   English

为什么 Ajax 调用在特定部分代码后不起作用?

[英]Why doesn't the Ajax call work after a certain part of the code?

I have a code in PHP and JS, where I use Vis.js to create a timeline and AJAX to make requests to a page to get a page as a response and put it inside a Bootstrap Modal.我在 PHP 和 JS 中有一个代码,我在其中使用 Vis.js 创建时间轴,并使用 AJAX 向页面发出请求以获取页面作为响应并将其放入 Bootstrap Modal 中。

Each user has an ID (in the div where the photo is) that when clicked opens the modal along with the page that was brought by the AJAX request.每个用户都有一个 ID(在照片所在的 div 中),单击该 ID 将打开模式以及 AJAX 请求带来的页面。 Until then, everything is fine.在那之前,一切都很好。 All AJAX requests to users work, the problem is with the timeline items.对用户的所有 AJAX 请求均有效,问题出在时间线项目上。

Each item should do the same thing as clicking on the user ID, but bring up a different page.每个项目都应该与单击用户 ID 执行相同的操作,但会调出不同的页面。 Up to item 6 works perfectly, however, after that, when I click on item 7 onwards nothing happens.最多第 6 项可以完美运行,但是,在那之后,当我点击第 7 项之后没有任何反应。 The number of users is also above 6, but one call works and the other does not.用户数也在6个以上,但是一个通话通,一个不通。

Does anyone have any idea why?有谁知道为什么?

This is the code:这是代码:

<script>

var now = Date.now();

var options = {
  stack: true,
  maxHeight: 640,
  horizontalScroll: true,
  verticalScroll: true,
  zoomKey: "ctrlKey",
  start: '2022-01-01',
  end: '2022-12-31',
  orientation: {
    axis: "top",
    item: "top",
  },
};

var groups = new vis.DataSet();
var items = new vis.DataSet();

var count = 300;

<?php

$query_todos = 'SELECT * FROM booking';
$todos_booking = $conn->prepare($query_todos);
$todos_booking->execute();

$combined = array();
$i = 0;

function sort_by_name($a,$b)
{
    return $a["nome_social"] > $b["nome_social"];
}

while($todos = $todos_booking->fetch(PDO::FETCH_ASSOC)){

  $query_nome = 'SELECT nomesocial, foto, situacao FROM dados WHERE iddados =:id_funcionario';
  $nome = $conn->prepare($query_nome);
  $nome->bindParam(':id_funcionario', $todos['id_funcionario'], PDO::PARAM_STR);
  $nome->execute();

  $nome_social = $nome->fetch(PDO::FETCH_ASSOC);

  if(!empty($nome_social['foto'])){
    $img = $nome_social['foto'];
  }else{
    $img = '../img/avatar.png';
  }

    if( ( $key = array_search( $todos['id_funcionario'], array_column( $combined, 'id_funcionario') ) ) !== false )  {
      $combined[$key]['projeto'] .= '||'.$todos['projeto'];
      $combined[$key]['software'] .= '|||'.$todos['software'];
      $combined[$key]['data_inicio'] .= '||'.$todos['data_inicio'];
      $combined[$key]['data_fim'] .= '||'.$todos['data_fim'];
      $combined[$key]['confirmacao'] .= '||'.$todos['confirmacao'];
      $combined[$key]['img'] = $img;
      $combined[$key]['nome_social'] = $nome_social['nomesocial'];
      $combined[$key]['situacao'] = $nome_social['situacao'];
    } else {
      $todos['img'] = $img;
      $todos['nome_social'] = $nome_social['nomesocial'];
      $todos['situacao'] = $nome_social['situacao'];
      $combined[] = $todos;
    }
  }

  $combined_nome_social = $combined;

  uasort($combined,"sort_by_name");

  foreach($combined as $chave => $valor){
?>

<?php

  if(!empty($valor['projeto'])){

    ?>

  groups.add({
    id: <?php echo $i; ?>,
    content: "<div id='<?php echo str_replace(' ', '',$valor['nome_social']); ?>' class='row justify-content-center cursor'><img src='<?php echo $valor['img']; ?>' style='width: 100px; height: 80px; border-radius: 100%;'><div class='row justify-content-center'><?php echo $valor['nome_social']; ?></div></div>",
    order: <?php echo $i; ?>,
    <?php if($valor['situacao'] == '0'){
       echo "style: 'background-color: rgba(255, 0, 0, 0.2)',
        className: 'red'"; 
       } ?>
  });

  <?php }else{ ?>
groups.add({
    id: <?php echo $i; ?>,
    content: "<div id='<?php echo str_replace(' ', '',$valor['nome_social']); ?>' class='row justify-content-center cursor'><img src='<?php echo $valor['img']; ?>' style='width: 100px; height: 80px; border-radius: 100%;'><div class='row justify-content-center'><?php echo $valor['nome_social']; ?></div></div>",
    order: <?php echo $i; ?>,
    <?php if($valor['situacao'] == '0'){
       echo "style: 'background-color: rgba(255, 0, 0, 0.2)',
       className: 'red'"; 
       } ?>
  });

  <?php } ?>

  setTimeout(function(){

$(document).ready(function(){
  $("#<?php echo str_replace(' ', '',$valor['nome_social']); ?>").click(function(){
    $("#editar_funcionario").html('');
    $.ajax({
          url: '../utilities/modal_adicionar_booking.php?id_funcionario=<?php echo $valor['id_funcionario']; ?>',
          method: 'GET',
          cache: false,
          contentType: false,
          processData: false,
          success: function(resultado){
  $form = $("<form id='adicionar_funcionario_booking' method='POST' enctype='multipart/form-data'></form>");
  $("#editar_funcionario").append($form);
  $("#adicionar_funcionario_booking").html(resultado);
  $("#titulo_editar").html('Adicionar booking de <?php echo $valor['nome_social']; ?>');
  let el = document.getElementById('editar');
  let modal =new bootstrap.Modal(el);
  modal.show();

  let confirmacao = document.getElementById('confirmacao');

  confirmacao.addEventListener('click', ()=>{
  if(confirmacao.checked){
      document.getElementById('label_confirmacao').innerHTML = "Confirmado";
  }else{
      document.getElementById('label_confirmacao').innerHTML = "Não confirmado";
  }
})

$("#botao_salvar").click(function(){
    $('#botao_salvar').prop('disabled', true);
        $('#botao_salvar').html('');
        $('#botao_salvar').append('<img src="../img/loading.gif" style="width: 30px;"/>');
    var dados = new FormData(document.getElementById("adicionar_funcionario_booking"));
      $.ajax({
            url: '../utilities/adicionar_booking.php?id_funcionario=<?php echo $valor['id_funcionario']; ?>',
            method: 'POST',
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            data: dados,
            success: function(resultado){
              let erros = ['erro_data_inicio', 'erro_data_fim'];
              let erros_select = ['erro_projeto', 'erro_software'];
              for (let i = 0; i < erros.length; i++) { 
                if((resultado[erros[i]]) && (resultado[erros[i]] != 'vazio')){
                $('#'+erros[i]).html(resultado[erros[i]]);
                $('#'+erros[i].replace('erro_', '')).removeClass();
                $('#'+erros[i].replace('erro_', '')).addClass('invalido form-control');

                $('#'+erros[i].replace('erro_', '')).on('input', ()=> {
                    $('#'+erros[i].replace('erro_', '')).removeClass();
                    $('#'+erros[i].replace('erro_', '')).addClass('form-control');
                    $('#'+erros[i]).html('');
                })
                }
              }
              for (let i = 0; i < erros_select.length; i++) {                 
                    if((resultado[erros_select[i]]) && (resultado[erros_select[i]] != 'vazio')){
                    $('#'+erros_select[i]).html(resultado[erros_select[i]]);
                    $('#'+erros_select[i].replace('erro_', '')+'_chosen').removeClass();
                    $('#'+erros_select[i].replace('erro_', '')+'_chosen').addClass('invalido chosen-container chosen-container-multi');
    
                    $('#'+erros_select[i].replace('erro_', '')).on('input', ()=> {
                        $('#'+erros_select[i].replace('erro_', '')+'_chosen').removeClass();
                        $('#'+erros_select[i].replace('erro_', '')+'_chosen').addClass('chosen-container chosen-container-multi');
                        $('#'+erros_select[i]).html('');
                    })
                    }
                    }
                    if(resultado.status){
                    modal.hide();
                    let status = document.createElement('div');
                    status.setAttribute("id", 'status');
                    document.body.appendChild(status);
                    $('#status').css({'position': 'fixed', 'top':'0', 'width':'100%', 'z-index':'100', 'text-align': 'center', 'color':'white', 'padding':'10px 10px 10px 10px', 
                    'font-size': '17px', 'background':'#0a5a0a'});
                    let progresso = document.createElement('span');
                    progresso.classList.add('progress-bar-fill');
                    progresso.style.cssText = 'width: 0%;';
                    $('#status').html(resultado.status);
                    document.getElementById('status').appendChild(progresso);
                    $('.progress-bar-fill').delay(50).queue(function () {
                        $(this).css('width', '100%')
                    });
                    setTimeout(() =>{
                        window.location.reload();
                    }, 1000);
                    $('#botao_salvar').remove();
                }
                $('#botao_salvar img:last-child').remove();
                $('#botao_salvar').html('Salvar alterações');
                $('#botao_salvar').prop('disabled', false);
            }
      })
    })

waitForElm('.chosen-select-software').then((elm) => {
      setTimeout(() =>{
    $.getScript('../bootstrap/_bootstrap/js/chosen_software.jquery.min.js', function() {
      console.debug('Script loaded.');
    });
    $.getScript('../bootstrap/_bootstrap/js/projeto_booking.js', function() {
      console.debug('Script loaded.');
    });
  }, 250);
});

}
})
})
})
}, 1000);

<?php
  $itens = explode('||', $valor['projeto']);
  $softwares = explode('|||', $valor['software']);
  $inicio = explode('||', $valor['data_inicio']);
  $fim = explode('||', $valor['data_fim']);
  $confirmacao = explode('||', $valor['confirmacao']);

  for($x = 0; $x < count($itens); $x++){

?>
  var start = '<?php echo $inicio[$x]; ?>';
  var end = '<?php echo $fim[$x]; ?>';

  <?php

  if(!empty($valor['projeto'])){

    ?>

  items.add({
    group: <?php echo $i; ?>,
    start: start,
    end: end,
    type: "range",
    content: "<div id='<?php $word = array_merge(range('a', 'z'), range('A', 'Z')); shuffle($word); $aleatorio = substr(implode($word), 0, 100); echo $aleatorio; ?>' title=' Projeto: <?php echo $itens[$x]; ?>&#10;Software: <?php echo str_replace('||', ', ', $softwares[$x]); ?>&#10;início: <?php echo date('d/m/Y', strtotime($inicio[$x])); ?>&#10;fim: <?php echo date('d/m/Y', strtotime($fim[$x])); ?>'><?php if($confirmacao[$x] == '0'){echo '<img src=\'../img/nao_confirmado.png\' style=\'width: 17px;\'><br>';}else{echo '<img src=\'../img/confirmado.png\' style=\'width: 17px;\'><br>';} ?><?php echo $itens[$x].'<br>'.str_replace('||', ', ', $softwares[$x]); ?></div>",
    className: '<?php echo $itens[$x]; ?>',
  });  


  $(document).ready(function(){
  setTimeout(function(){
    $("#<?php echo $aleatorio; ?>").click(function(){

      editarBooking();

    })

      function editarBooking(){
      $("#editar_funcionario").html('');
      $.ajax({
            url: '../utilities/modal_editar_booking.php?id_funcionario=<?php echo $valor['id_funcionario']; ?>&projeto=<?php echo $itens[$x]; ?>&data_inicio=<?php echo $inicio[$x]; ?>&data_fim=<?php echo $fim[$x]; ?>&software=<?php echo $softwares[$x]; ?>&confirmacao=<?php echo $confirmacao[$x]; ?>',
            method: 'GET',
            cache: false,
            contentType: false,
            processData: false,
            success: function(resultado){
    $form = $("<form id='editar_funcionario_booking' method='POST' enctype='multipart/form-data'></form>");
    $("#editar_funcionario").append($form);
    $("#editar_funcionario_booking").html(resultado);
    $("#titulo_editar").html('Editar booking de <?php echo $valor['nome_social']; ?>');
    let el = document.getElementById('editar');
    let modal =new bootstrap.Modal(el);
    modal.show();

    let confirmacao = document.getElementById('confirmacao');

    confirmacao.addEventListener('click', ()=>{
    if(confirmacao.checked){
        document.getElementById('label_confirmacao').innerHTML = "Confirmado";
    }else{
        document.getElementById('label_confirmacao').innerHTML = "Não confirmado";
    }
})

  $("#botao_salvar").click(function(){
    $('#botao_salvar').prop('disabled', true);
        $('#botao_salvar').html('');
        $('#botao_salvar').append('<img src="../img/loading.gif" style="width: 30px;"/>');
    var dados = new FormData(document.getElementById("editar_funcionario_booking"));
      $.ajax({
            url: '../utilities/editar_booking.php?id_funcionario=<?php echo $valor['id_funcionario']; ?>&projeto=<?php echo $itens[$x]; ?>&data_inicio=<?php echo $inicio[$x]; ?>&data_fim=<?php echo $fim[$x]; ?>&software=<?php echo $softwares[$x]; ?>&confirmacao=<?php echo $confirmacao[$x]; ?>',
            method: 'POST',
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            data: dados,
            success: function(resultado){
              let erros = ['erro_data_inicio', 'erro_data_fim'];
              let erros_select = ['erro_projeto', 'erro_software'];
              for (let i = 0; i < erros.length; i++) { 
                if((resultado[erros[i]]) && (resultado[erros[i]] != 'vazio')){
                $('#'+erros[i]).html(resultado[erros[i]]);
                $('#'+erros[i].replace('erro_', '')).removeClass();
                $('#'+erros[i].replace('erro_', '')).addClass('invalido form-control');

                $('#'+erros[i].replace('erro_', '')).on('input', ()=> {
                    $('#'+erros[i].replace('erro_', '')).removeClass();
                    $('#'+erros[i].replace('erro_', '')).addClass('form-control');
                    $('#'+erros[i]).html('');
                })
                }
              }
              for (let i = 0; i < erros_select.length; i++) {                 
                    if((resultado[erros_select[i]]) && (resultado[erros_select[i]] != 'vazio')){
                    $('#'+erros_select[i]).html(resultado[erros_select[i]]);
                    $('#'+erros_select[i].replace('erro_', '')+'_chosen').removeClass();
                    $('#'+erros_select[i].replace('erro_', '')+'_chosen').addClass('invalido chosen-container chosen-container-multi');
    
                    $('#'+erros_select[i].replace('erro_', '')).on('input', ()=> {
                        $('#'+erros_select[i].replace('erro_', '')+'_chosen').removeClass();
                        $('#'+erros_select[i].replace('erro_', '')+'_chosen').addClass('chosen-container chosen-container-multi');
                        $('#'+erros_select[i]).html('');
                    })
                    }
                    }
                    if(resultado.status){
                    modal.hide();
                    let status = document.createElement('div');
                    status.setAttribute("id", 'status');
                    document.body.appendChild(status);
                    $('#status').css({'position': 'fixed', 'top':'0', 'width':'100%', 'z-index':'100', 'text-align': 'center', 'color':'white', 'padding':'10px 10px 10px 10px', 
                    'font-size': '17px', 'background':'#0a5a0a'});
                    let progresso = document.createElement('span');
                    progresso.classList.add('progress-bar-fill');
                    progresso.style.cssText = 'width: 0%;';
                    $('#status').html(resultado.status);
                    document.getElementById('status').appendChild(progresso);
                    $('.progress-bar-fill').delay(50).queue(function () {
                        $(this).css('width', '100%')
                    });
                    setTimeout(() =>{
                        window.location.reload();
                    }, 1000);
                    $('#botao_salvar').remove();
                }
                $('#botao_salvar img:last-child').remove();
                $('#botao_salvar').html('Salvar alterações');
                $('#botao_salvar').prop('disabled', false);
            }
      })
    })

    waitForElm('.chosen-select-software').then((elm) => {
      setTimeout(() =>{
    $.getScript('../bootstrap/_bootstrap/js/chosen_software.jquery.min.js', function() {
      console.debug('Script loaded.');
    });
    $.getScript('../bootstrap/_bootstrap/js/projeto_booking.js', function() {
      console.debug('Script loaded.');
    });
  }, 250);
});
    }
  })
}
})}, 1000);

<?php }else{ ?>

  items.add({
    group: <?php echo $i; ?>,
    start: '<?php echo  date('Y-m-d', strtotime('-4 month', strtotime(date('Y-m-d')))); ?>',
    end: '<?php echo  date('Y-m-d'); ?>',
    content: '<div class="row justify-content-center">NENHUMA INFORMAÇÃO DE BOOKING ENCONTRADA</div>',
  });  


<?php
}
}
$i++;
}
?>


// create a Timeline
var container = document.getElementById("booking");
timeline = new vis.Timeline(container, null, options);
timeline.setGroups(groups);
timeline.setItems(items);

function debounce(func, wait = 100) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

function move(percentage) {
  var range = timeline.getWindow();
  var interval = range.end - range.start;

  timeline.setWindow({
    start: range.start.valueOf() - interval * percentage,
    end: range.end.valueOf() - interval * percentage,
  });
}

document.getElementById("zoomIn").onclick = function () {
  timeline.zoomIn(0.5);
};
document.getElementById("zoomOut").onclick = function () {
  timeline.zoomOut(0.5);
};
document.getElementById("moveLeft").onclick = function () {
  move(0.2);
};
document.getElementById("moveRight").onclick = function () {
  move(-0.2);
};

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}
</script>

This is the timeline:这是时间线:

timeline时间线

In case someone needs it, I'll leave the solution here, even if I find it difficult for someone to need it.万一有人需要它,我会把解决方案留在这里,即使我发现有人很难需要它。

After a lot of breaking my head doing tests, I realized the following:经过大量的测试后,我意识到以下几点:

Items are only created as the scroll goes down and the groups appear.只有当滚动向下并且组出现时才会创建项目。

That is, when I put the events for items that are not visible on the screen, they were not created, so there is no way to call the event, because its ID does not exist yet.也就是说,当我把不可见的项目的事件放在屏幕上时,它们没有被创建,所以没有办法调用事件,因为它的 ID 还不存在。

The solution was to use the MutationObserver API to check when the element exists on the page and apply a function to it.解决方案是使用 MutationObserver API 检查元素何时存在于页面上并对其应用 function。

<script>
   function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM