0

I have this line of code :

$.ajax({
    url: "ViewQuiz.aspx/SetAllQuestionsByQuizId",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data: "{'quizId':'" + quizId + "'}",
    success: function (data) {
        htmlString += '<select class="inputTextStyle selectAnswerToQuestion">';
        $.map(data.d, function (item) {
            htmlString += '<option value="' + item.QuestionId + '">' + item.QuestionContent + '</option>';

        });
        htmlString += '</select>';


    },
    error: function (result) {

    }

});

return htmlString;

the htmlString is returning nothing. although if I console.log the item, its returning my objects.

why ?

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
thormayer
  • 1,070
  • 6
  • 28
  • 49

1 Answers1

4

Ajax means Asynchronous execution, control will move further once the request is made.It wont wait for return of ajax call.
In your example Ajax call will be made and when control reaches to return statement success function may/may not been executed so its returning nothing.
You should do the required things in success function itself.

success: function (data) {
        //...........
        htmlString += '</select>';
        // Do the required things here instead of returning `htmlString`

    },

Realted question How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Ajinkya
  • 22,324
  • 33
  • 110
  • 161