In the function below, I have this 2 variables, size and total, which should be acessible in the entire function block, but when the execution arrives in the third if, they present the value undefined:
function update_cart() {
  var cart_size = document.getElementById('cart_size');
  var cart_status = document.getElementById('cart_status');
  var cart_total = document.getElementById('cart_total');
  var size, total;
  if(cart_size !== null) {
    var cliente = cart_size.dataset.cliente;
    var url = cart_size.dataset.url;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        size = xhr.responseText;
        cart_size.innerHTML = size;
        if(size == 0)
          cart_size.style.display = 'none';
        else
          cart_size.style.display = 'block';
      }
    };
    var formData = new FormData();
    formData.append("cliente", cliente);
    xhr.send(formData);
  }
  if(cart_total !== null) {
    var cliente = cart_total.dataset.cliente;
    var url = cart_total.dataset.url;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        total = xhr.responseText;
        var currency = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(total);
        cart_total.innerHTML = currency;
      }
    };
    var formData = new FormData();
    formData.append("cliente", cliente);
    xhr.send(formData);
  }
  if(cart_status !== null) {
    switch(size) {
      case 0:
        cart_status.innerHTML = 'A cesta de compras está vazia.';
        document.getElementById('table').style.display = 'none';
        break;
      case 1:
        cart_status.innerHTML = size + ' produto adicionado na cesta, com valor ' + total;
        document.getElementById('table').style.display = 'block';
        break;
      default:
        cart_status.innerHTML = size + ' produtos adicionados na cesta, com valor ' + total;
        document.getElementById('table').style.display = 'block';
        break;
    }
  }
}
I already tried declare them with var and let, with the same result. In the page where cart_status exists, both cart_size and cart_total exists.
Anyone can give a hint of how fix that issue?
 
     
     
    