-1

I get a JSON from a REST API through Ajax if i write the result into console and copy it into a string variable (jsonInput) JSON.parse works fine, but if i directly use data(ajax result)it is undefined. I checked both variables and there are equal?

let jsonInput = 
  '{"pollId":49,
    "question":"sdf",
    "multipleAnswer":0,"answers":
     [{"pollAnswerId":69,"answer":"sdf"},
      {"pollAnswerId":70,"answer":"fsdf"}]}'

console.log(data === jsonInput); //TRUE

json = JSON.parse(data); //undefined

json = JSON.parse(jsonInput); //succesfull parsed
Brhaka
  • 1,622
  • 3
  • 11
  • 31
djkobi97
  • 77
  • 6
  • 2
    From the answer(?) below, this is an issue with misunderstanding how asynchronous requests work. Ref. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Taplar Dec 31 '18 at 16:04

3 Answers3

1

Don't quote it as a string. It's an object.

let jsonInput = {...}
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

Though you have not defined your question with complete code. But it could be one of the reasons that data is a string but not a JSON Object.

shivanisdev
  • 687
  • 6
  • 16
0

I think i found the main problem, json is init with data but outsite the .ajax json is undefined

       let json;
       $.ajax({
        url : "http://localhost:4040/api/"+id,
        type: "POST",
        success: function(data){
           console.log(data); //works fine
           json = data;
           console.log(json); //works fine
        }
    });
    console.log(json); //undefined
djkobi97
  • 77
  • 6