0

Sorry for the simple question, I am new to Javascript and Ajax. Here is my code:

var rootURL = "http://localhost:8080/WineCellar/rest/wines";

var findById= function(id){
    var testWine;
    console.log('findById: ' + id);
    $.ajax({
        type: 'GET',
        url: rootURL + '/' + id,
        dataType: 'json',
        success: function(data){
            console.log('findById success: '+ data.name);
            testWine = data;
        }
    });
    return testWine;
};


var myWine = findById(3);
console.log(myWine.name);

It gives the following console output: https://i.stack.imgur.com/JqmHQ.png

Cannot read property 'name' of undefined

myWine is undefined. How do I fix this? Is it possible there are two ways of overcoming this problem? Perhaps I need to add a parameter to the ajax method?

CoJ265
  • 21
  • 4

1 Answers1

0

Perhaps you could try using the fetch API ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ) heres an example

let YOUR_API = "https://swapi.dev/api/people/1/";
let cache;

window.onload = function () {
    fetch(YOUR_API)
    .then((response) => response.json())
    .then((myJsonResponse) => {
        cache = myJsonResponse;
        console.log(cache);
        // the rest of the code that runs on this response
    });
};
Mario Perez
  • 2,777
  • 1
  • 12
  • 21
  • It's the same fundamental problem - the request would still be asynchronous. – VLAZ Apr 28 '20 at 20:20
  • it seems like the users problem is "myWine is undefined. How do I fix this? " once myWine is defined he can process it however he needs to – Mario Perez Apr 28 '20 at 20:25
  • Yes Mario, more specifically how do I define myWine in this context? – CoJ265 Apr 28 '20 at 20:33
  • @MarioPerez it's undefined *because it's incorrectly returned*. Changing from `$.ajax` to `fetch` and not dealing with the asynchronisity, then nothing will change. – VLAZ Apr 28 '20 at 20:45