-2

I'm attempting to do a simple get query on JavaScript to retrieve a JSON string.

This is what I've tried:

  var response = $.get('https://uselessfacts.jsph.pl/random.json? 
  language=en') ;


  var answer = JSON.stringify(response);


  document.write(answer);

I am receiving the output : {"readyState":1}

I do not know what the problem is.

Appreciate the help.

Newton
  • 25
  • 7
  • Not a duplicate. It's linked to my previous question which I have posted. – Newton Aug 03 '19 at 15:40
  • 1
    `$.get()` returns a Promise; it is not the content returned from the HTTP request. – Pointy Aug 03 '19 at 15:41
  • `$.get` is an asynchronous call. You have the wait for the code to make the request before trying to use it's response. – Luca Kiebel Aug 03 '19 at 15:41
  • 3
    Read the `$.get()` documentation!! – charlietfl Aug 03 '19 at 15:42
  • @charlietfl If you're going to tell someone to read the documentation, the least you can do is provide a [link to the documentation](https://api.jquery.com/jquery.get/). – Makyen Aug 03 '19 at 15:45
  • @Makyen Is it really that difficult to find? – charlietfl Aug 03 '19 at 15:46
  • 1
    @charlietfl Why did you close and then reopen this question? How is this *not* a duplicate of the canonical [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321) – Makyen Aug 03 '19 at 15:47

1 Answers1

0

You need to pass a function in $.get which will serve as a callback for your request:

$.get( "https://uselessfacts.jsph.pl/random.json?language=en", function(data) {
  var answer = JSON.stringify(data);
  document.write(answer);
});
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43