-1

So my current scenario is I want to fetch JSON data from an URL, parse it and assign it to a window variable. So the code is as following:

$.getJSON('https://apiv3.iucnredlist.org/api/v3/species/citation/loxodonta%20africana?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee', function(data) {
     var id = data.result[0].taxonid;
});

window.speciesId = id;

console.log(window.speciesId);

Is this or something similar possible in JavaScript / jQuery? I'm not very familiar with JS so therefore would be grateful if a workaround can be suggested.

  • 1
    You can certainly assign the data to a global / window scoped variable but it won't be available outside of the callback function until the request has resolved. – Phil Mar 31 '20 at 02:52

1 Answers1

-1

You can use ajax:

$.ajax('http://dummy.restapiexample.com/api/v1/employees',   // request url
    {
        success: function (data, status, xhr) {    // success callback function
           console.log(data);    //data received
    }
});

Don't forget to import jquery:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Akash Bhardwaj
  • 346
  • 1
  • 3
  • 9
  • OP is already using `$.getJSON()` which is a wrapper function for `$.ajax()` – Phil Mar 31 '20 at 02:53
  • OP's question appears to primarily be about assigning a value from an AJAX response to a globally scoped variable – Phil Mar 31 '20 at 03:10