Ajax call not (quite) working

I have 2 select form elements named client and matter. The first is populated by PHP; the second is populated using an Ajax call, depending on the client entered. This all works okay. What I want is when a matter is selected to get a balance figure using Ajax, which depends on the cid and mid.

Since cid is out of range for the second Ajax call I have repeated the assignment, but it always seems to return an empty string (or null).

Where am I going wrong?

Here is my JS:

  const clist = document.getElementById("client");
  const mlist = document.getElementById("matter");
  clist.addEventListener("change", function() {
    const cid = clist.options[clist.selectedIndex].value;
    fetch("getMatters.php?c="+cid)
    .then (response => {
      mlist.innerHTML = "Waiting for response...";
      if (response.ok)
        return response;
      throw Error(response.statusText);
    })
    .then (response => response.text())
    .then (text => mlist.innerHTML = text)
    .catch (error => console.log("There was an error:", error))
  });

  const clbal = document.getElementById("balance");
  const cid = clist.options[clist.selectedIndex].value;
  mlist.addEventListener("change", function() {
    const mid = mlist.options[mlist.selectedIndex].value;
    fetch("getCLBalance.php?c="+cid+"&m="+mid)
    .then (response => {
      clbal.value = "Waiting for response...";
      if (response.ok)
        return response;
      throw Error(response.statusText);
    })
    .then (response => response.text())
    .then (text => clbal.value = text)
    .catch (error => console.log("There was an error:", error))
  });

FWIW I have my half-working code here gand al f458. co.u k/vir go/virg o1.php

Because your definition for cid is external to the eventListener?

So it’s at the global level, is evaluated on load (which, on load, clist has no selected value, so it gets “”), and your function trigger doesnt reevaluate it as your first function does (creating a local-to-the-function version of cid, which is a constant), it uses the global scoped value as a fallback.

EDIT: er… clist not mlist.

Something to take away from this: getting a reference to an element is a living pointer; getting the value of an element is a dead string/integer return.

1 Like

Oh der! And I thought I’d tried that. Thanks.

I think the mist is clearing… just a little. :cloud:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.