Reputation: 19
I am new to JavaScript and AJAX. I am getting the below error:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 92 of the JSON data in javascript
I searched a lot in Google, but I can't find a solution. One more thing, if I have one only record in the database, my code works fine; but if I insert another row in the database, I get the error. Please help me to resolve this, find my code below:
$.ajax({
type: "POST",
//dataType: "json",
url: "./QuizServlet",
success: function (responseText) {
alert("alert" + responseText);
var jsonData = JSON.parse(responseText);
for (var i = 0; i < jsonData.length; i++) {
var questions;
choice = jsonData[i].options;
ch = choice.split(",");
console.log(ch);
questions = [{ question: questionnn, choices: ch, correctAnswer: answer }];
}
}
});
Again, the issue is coming while fetching more than one row from database.
i have added the servlet code from where is returing json output.
List<QuizDto> quiz=new ArrayList<QuizDto>();
quiz=QuizDao.quizdetails();
JSONArray jsonarray= new JSONArray();
for(int i=0;i<quiz.size();i++)
{
JSONObject obj = new JSONObject();
//obj.put("issueno", quiz.get(i).getIssueno());
obj.put("questions",quiz.get(i).getQuestions());
obj.put("answers",quiz.get(i).getAnswers());
obj.put("options", quiz.get(i).getOptions());
jsonarray.put(obj);
System.out.println("Json in Servelt"+ jsonarray.toString());
response.getWriter().print(jsonarray);
}
i am prininting output in sysout, it is returning only 2 uniques records correctly.
Json in Servelt[{"answers":1,"questions":"what is correct answer","options":"first,second,third,fourth,"},{"answers":2,"questions":"what is quiz","options":"quiz,output,answer,question"}]
but, while in javascript, ResponseText is displaying the 1 row repeated two times as shown below:
alert[{"answers":1,"questions":"what is correct answer","options":"first,second,third,fourth,"}][{"answers":1,"questions":"what is correct answer","options":"first,second,third,fourth,"},{"answers":2,"questions":"what is quiz","options":"quiz,output,answer,question"}]
not able to understand why it is happening
Upvotes: 2
Views: 5661
Reputation: 1373
The response you're returning is probably not in JSON format. The most common issue is not adding quotes in object keys.
According to the data you're sending, you're actually sending several concatenated JSONs (several arrays not encapsulated and not separated with commas).
this should be [[...],[...],[...]]
instead of [...][...][...]
as you have now.
Upvotes: 3