2

enter image description hereI have a jQuery call which is getting the data in to a object. I'm trying to use the object value to set as a label text from javascript, but it throws

"Cannot read property '0' of undefined."

where as it prints the value successfully to the console.

var questionData;
var optionData;

$(document).ready(function () {    
    $.ajax({
        url: 'coaching-assessment-tool.aspx/GetCATQuestionAndOptions',
        type: 'POST',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {            
            questionData = data.d[0];
            optionData = data.d[1];           
            console.log(questionData[0].QuestionText);
            console.log("Question Data", questionData);
            console.log("Option Data", optionData);
        },
        error: function (error) {
            console.log(error);
            alert('Error retrieving data. Please contact support.');
        }        
    });
    document.getElementById('firstQuestion').innerHTML = questionData[0].QuestionText;
});

I need the label text as the object value (questionData[0].QuestionText).enter image description here

crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
Ananth Asamani
  • 207
  • 2
  • 15
  • 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) –  May 16 '19 at 18:45
  • Live console output will update when the object changes. –  May 16 '19 at 18:46

1 Answers1

4

$.ajax() is asynchronous by default, so setting innerHTML is happening before questionData is populated. Move line 22 inside the success callback to make sure the data is available before it is used.

While it's technically possible to make the call synchronous, it's a bad idea.

$.ajax({
   // ...
   async: false,
   // ...
});

That code would prevent any other JavaScript from executing until the ajax call is complete.

Just as an aside, some JavaScript tooling like TypeScript can help you catch those mistakes before the code executes in a browser. I've recently converted some JS to TS and been very happy with the number of bugs I've caught.

Cheers!

crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
  • Thank you so much Michael, it did work, I appreciate it. – Ananth Asamani May 16 '19 at 18:46
  • You bet! If it completely fixed your issue, please mark the answer as correct. It'll help other folks find answers to similar issues. :-) – crenshaw-dev May 16 '19 at 18:50
  • 1
    Yeah I did mark it, I hope some day I'll work on TS, I'm more of a .net developer actually. Thanks for the help. Since you are here shall I ask you another question? – Ananth Asamani May 16 '19 at 19:07
  • The `$.ajax({ async: false })` call is just a partial example of a synchronous call, to show what it would look like. You'd have to provide additional options for it to actually do anything useful. – crenshaw-dev May 16 '19 at 19:11
  • I couldn't paste the code in the comment var ddlFirstResponse = $('#ddlFirstResponse'); ddlFirstResponse.empty(); ddlFirstResponse.append($("").val('').html('')); $.each(data, function (i, optionData) { ddlFirstResponse.append($("").val(optionData.OptionId).html(optionData.OptionText)); }); – Ananth Asamani May 16 '19 at 19:17
  • I added that after the line 22 in the javascript, it doesn't throw error not output it gives – Ananth Asamani May 16 '19 at 19:18
  • Ah, gotcha. I think I can help with that, but I don't think it's related to the `undefined` issue. Please open a new question with details about this problem, and I'll try to help! – crenshaw-dev May 16 '19 at 19:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/193494/discussion-between-michael-crenshaw-and-ananth-asamani). – crenshaw-dev May 16 '19 at 19:29