0

I'm trying to filter a json array based on a value from a url and get the vernacularName attribute. In the F12 debugging I can put record[0].vernacularName; and it gives me the correct variable, but still the below code fails.

document.getElementById("demo").innerHTML = datasetID; works but document.getElementById("demo").innerHTML = vernacularName; does not.

Ultimately I want to add vernacularName as a session variable

<body>
  <div class="">
    <h3>testing data</h3>
  <p id="demo" class = 'pl-5'></p>    
  </div>



<script type="text/javascript">
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);

  const species = urlParams.get('species')
  const bone = urlParams.get('bone')

  const datasetID = urlParams.get('datasetID')

  var data;
  $.getJSON("json/data.json", function(json){
    data = json;
  });

  record = data.filter(r => r.datasetID == datasetID);


  var vernacularName = record[0].vernacularName;
  // const vernacularName2 = record.vernacularName;
  $_SESSION["v"] = vernacularName;


</script>

<script>
document.getElementById("demo").innerHTML = vernacularName;
</script>
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37

1 Answers1

1

Firstly, I'm not sure why

document.getElementById("demo").innerHTML = vernacularName;

is within in its own script tag. That seems quite odd.

In any case, the issue here is that the data is not ready yet. You can't start to process the data & use it to update elements on the page until the data has been returned to you.

That's the whole point of the second argument to getJSON - its a function called upon success, after the data has been fetched.

Hence, the rest of your code should all go inside that function:

  $.getJSON("json/data.json", function(json) {
    const data = json;
    const record = data.filter(r => r.datasetID === datasetID);
    const vernacularName = record[0].vernacularName;
    $_SESSION["v"] = vernacularName;
    document.getElementById("demo").innerHTML = vernacularName;
  });

Side note: Since it appears you're using ES6+, then you shouldn't be using var unless you have a good reason to. Use let instead. There's information about it here and in this post. However, in this case, everything in your code is constant, so stick to const.

costaparas
  • 5,047
  • 11
  • 16
  • 26