0

I am trying to load a data from a url to a variable using .ready() but the alert box provides a undefined value, please help.

    let getMasterProd = () => {
        return fetch('url').then(data => data.json());
    }



    $( document ).ready(function() {
        var data =getMasterProd();
        alert(data);
    });
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Durga Jan 10 '19 at 10:24

4 Answers4

1

The reason for 'undefined' is probably because of the async nature of the fetch call. If you really want to provide the alert try using it inside then():

fetch('url').then(function(data){alert(data)});

You can also use async ajax call to fetch data but this is not recommended. If you can provide actual scenario then it will be more convenient for me to answer. Or you can try something suggested previously:

 let test;
console.log(fetch('url').then(function (data) {
  test = data;
}));
setTimeout(function () {
  alert(test);
}, 500);

For detail refer: How do I return the response from an asynchronous call?

Akshay Mishra
  • 189
  • 1
  • 8
0

I think this should also work:

  function $_GET(q, s) {
    s = (s) ? s : window.location.search;
    var re = new RegExp('&' + q + '=([^&]*)', 'i');
    return (s = s.replace(/^\?/, '&').match(re)) ? s = s[1] : s = '';
  }

Just call it like this:

var value = $_GET('myvariable');
agravat.in
  • 561
  • 6
  • 14
0

fetch returns a Promise not data.

const getMasterProd = () => fetch('url').then(data => data.json());

$(document).ready(() => {
    getMasterProd()
    .then((data) => {
      alert(data);
    });
});
Martial
  • 1,446
  • 15
  • 27
-1

Give this a try,

fetch('url').then(data => { return data.json() });

Also, you should consider using axios.

user3362908
  • 433
  • 5
  • 16