0

Currently I have an AJAX request which will run the following SQL statement.

select top 1     
         DrugQuestionId
        ,DrugId
        ,DrugQuestion as DrugQuizquestion
        ,CorrectAnswer
        ,QuizQuestionTypeId
from DrugQuestions

and return me one drugQuestion object, with the properties listed in the SQL Server table.

pertinent JS:

$(document).ready(function ()
        {
            $('#btnSubmit').click(function ()
            {
                $.ajax(
                {
                    type: "POST",
                    url: "GetDrugQuiz.asmx/GenerateDrugQuestion",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        var drugQuestion = $.parseJSON(data.d);
                        //everything prints to the console correctly
                        console.log(drugQuestion.DrugQuestionId); //5 in this example
                        console.log(drugQuestion.DrugId);
                        console.log(drugQuestion.DrugQuizQuestion);
                        console.log(drugQuestion.CorrectAnswer);
                        console.log(drugQuestion.QuizQuestionTypeId);


                    },
                    error: function (xhr)
                    {
                        alert(xhr.status);
                    }

                });
            });
        });

This works fine and gives me the answer I was looking for. In practice, I need a drugQuiz object which has a property which is an array of drugQuestion objects. I used the following WebMethod to attempt that:

//this is questions, plural mean to populate an array with a length equal to the row count
//of the query
     public string GenerateDrugQuestions()
            {
                var jss = new JavaScriptSerializer();
                DrugQuiz qz = new DrugQuiz();
                qz.PatientId = 123;
                qz.DateTaken = DateTime.Now;
                qz.DrugQuizId = 1;
                string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
                using (var con = new SqlConnection(cs))
                {
                    using (var cmd = new SqlCommand("select top 3 * from DrugQuestions", con))
                    {
                        con.Open();

                        SqlDataReader rdr = cmd.ExecuteReader();
                        while (rdr.Read())
                        {
                            DrugQuestion dq = new DrugQuestion();
                            dq.DrugQuestionId = (int)rdr["DrugQuestionId"];
                            dq.DrugId = (int)rdr["DrugId"];
                            dq.DrugQuizQuestion = rdr["DrugQuestion"].ToString();
                            dq.CorrectAnswer = rdr["CorrectAnswer"].ToString();
                            dq.QuizQuestionTypeId = (int)rdr["QuizQuestionTypeId"];
                            qz.DrugQuestions.Add(dq);
                        }
                        return jss.Serialize(qz);
                    }
                }
            }

So you can see that a JSON string is being returned from the WebMethod. When I use the WebMethod without actually visiting the page and hit Invoke, I get the correct string. What I can't figure out is how to populate an array of drugQuestions, which is a property of a drugQuiz object. What do I need to change about the following code to allow that to happen?

$(document).ready(function ()
        {
            var drugQuiz = {};
            drugQuiz.drugQuestions = new Array();
            $('#btnSubmit').click(function ()
            {
                $.ajax(
                {
                    type: "POST",
                    url: "GetDrugQuiz.asmx/GenerateDrugQuestions",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        drugQuiz.drugQuestions.push($.parseJSON(data.d));
                        console.log(drugQuiz.drugQuestions.length);
                        console.log(drugQuiz.drugQuestions);

                    },
                    error: function (xhr)
                    {
                        alert(xhr.status);
                    }

                });
            });
        });

I need to be able to do something like alert(drugQuiz.drugQuestions[0].DrugId);

1 Answer 1

3

Loop through the returned JSON and push each item into the JavaScript array, like this:

success: function (data) {
    $.each(data.d, function(i, item) {
        drugQuiz.drugQuestions.push(item);
    });
},

If you want to do this with parseJSON(), then try this:

success: function (data) {
    var jsonData = JSON.parse(data.d);
    for (var i in jsonData.drugQuestions) {
        var question = jsonData.drugQuestions[i];
    }
},

Note: I am not sure of the names of your JSON objects, I am guessing that drugQuestions is the name of the array of drugQuestion objects passed back, if it is not, then change the jsonData. value to match the structure of your JSON returned.

Sign up to request clarification or add additional context in comments.

2 Comments

Can this be done without using each (just for curiosity's sake). When I look at what comes to the console when I use var string = $.parseJSON(data.d) it looks like it has all of the data in there, but if I try to use an indexer to access a property, it's undefined.
Yes, but I find the .each() syntax to be much cleaner, but with that said the question has been updated to show the .parseJSON() syntax as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.