-1

I got a piece of code in here:

$.get("/upcase", {text: text})
.done((data) => {
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val(''); // reset the textbox
});

Usually the data data['result'] will be pass to a html <ul>tag with id="results" to form a list, but what if I want to store it into a variable, how do I achieve that?

At least it does not work like this:

let something = $('#results').val(data['result']);
Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51
Travis Su
  • 670
  • 2
  • 7
  • 17
  • `let something = data['results'];` – CodingYoshi Dec 07 '17 at 23:11
  • @CodingYoshi it shows 'undefined' when I print it – Travis Su Dec 07 '17 at 23:14
  • probably because you are not printing it within the scope of `.done`. If you need it outside, see the answer below. – CodingYoshi Dec 07 '17 at 23:18
  • 1
    Sorry, didn't mean to close the question - possibly a dupe of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call - but not sure as the question is poorly written – Jaromanda X Dec 07 '17 at 23:19
  • 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) – nyedidikeke Dec 07 '17 at 23:52

1 Answers1

2

declare a variable outside what you have, and in scope of where you need it. Say global. then just assign the data to it. i.e.

let globalResult;   
$.get("/upcase", {text: text})
  .done((data) => {
    globalResult = data;
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val('');   // reset the textbox
  })

just remember that data will be an object and get copied by reference, not value. So if you change data or globalData it will change the other. If that is no good you need to actually copy each element across.

andrewf
  • 375
  • 4
  • 10
  • so I tried `globalresult = data['result']`, the data did pass though. But went I try to print it outside of the `$.get` scope, it shows `Variable might not have been initialized`, why? – Travis Su Dec 07 '17 at 23:23
  • probably because you are printing it before the async request has returned. and I didn't initialize it. so change it to let globalResult = {}; and it will print an empty object. it won't have content until the get has returned. – andrewf Dec 07 '17 at 23:25