1

I'm trying to retrieve the data from the database using the json object. But when i call the servlet, the Jquery will returns SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data This error only shows when the response contains more data.

My script is :

    $.ajax({
       type: "GET",
        url: "VComment",
        data:'comm='+encodeURIComponent(comm)+'&'+'data-id='+encodeURIComponent(dataid)+'&'+'data-alid='+encodeURIComponent(dataalid),
        dataType: "json",
        success: function( data, textStatus, jqXHR) 
        {
            if(data.success)
            {
                    var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix"> <section class="c-author">';
                    newcommhtml = newcommhtml + '<h3>Anonymous</h3>';
                    newcommhtml = newcommhtml + '<span class="pubdate">'+month+' '+day+', '+year+'</span> </section>';
                    newcommhtml = newcommhtml + '<section class="c-content">';
                    newcommhtml = newcommhtml + '<img src="images/green-avatar.png" alt="avatar" width="80" height="80" class="ava">';
                    newcommhtml = newcommhtml + '<p>'+nl2br(data.commentInfo.comment)+'</p> </section></div>';

                    var thelm = "#c0"+thecid;
                    commwrap.append(newcommhtml);
                    $(thelm).hide().fadeIn('slow');

                    setTimeout(function() { $(thelm).addClass('green'); }, 800);

                    $("#comm").val("");
                    thecid++;

                    if(errorspan.html() != null) {
                        errorspan.remove();
                    }
            }

          },
     error: function(jqXHR, textStatus, errorThrown)
      {
         alert("error"+errorThrown);
         console.log("Something really bad happened " + textStatus);
      },
});

And the response received..

    {"success":true,"commentInfo":{"uname":"shyam","comment":"rreter","itemId":0}}
    {"success":true,"commentInfo":{"uname":"shyam","comment":"dfdsfdd","itemId":0}}
    {"success":true,"commentInfo":{"uname":"shyam","comment":"xzdfdsfdd","itemId":0}}
    {"success":true,"commentInfo":{"uname":"shyam","comment":"sdfsd fsdfs","itemId":0}}
    {"success":true,"commentInfo":{"uname":"shyam","comment":"sdsd","itemId":0}}
    {"success":true,"commentInfo":{"uname":"shyam","comment":"dd","itemId":0}}
    {"success":true,"commentInfo":{"uname":"shyam","comment":"dddf","itemId":0}}

Servlet code :

      while(rs.next()){
            Commenter comment = new Commenter();
            comment.setUname(rs.getString("uname").trim());
            comment.setComment(rs.getString("comments").trim());
            commentObj=gson.toJsonTree(comment);
            myObj.add("commentInfo", commentObj);
            out.println(myObj.toString());
            }   

Please anyone tell me how to solve this problem ... Thanks....

4
  • 1
    Well, the response is not valid JSON. {...} {...} is not valid. {...} and [{...},{...}] would be. Fix your server code yo create valid JSON. Commented Feb 21, 2013 at 13:30
  • The output is not valid JSON, so jQuery is not able to parse it. Commented Feb 21, 2013 at 13:30
  • @Felix Kling But I don't know how to pass it in array from servlet. Please tell me how to pass the values in array...I tried this in different ways but none of them are worked for me.... Commented Feb 21, 2013 at 13:31
  • Convert an array of comments to JSON. Commented Feb 21, 2013 at 13:32

3 Answers 3

3

You have several indenpendant JSON objects in the response. Wrap them in an array and you will be better off

[{"success":true,"commentInfo":{"uname":"shyam","comment":"rreter","itemId":0}},
{"success":true,"commentInfo":{"uname":"shyam","comment":"dfdsfdd","itemId":0}},
{"success":true,"commentInfo":{"uname":"shyam","comment":"xzdfdsfdd","itemId":0}},
{"success":true,"commentInfo":{"uname":"shyam","comment":"sdfsd fsdfs","itemId":0}},
{"success":true,"commentInfo":{"uname":"shyam","comment":"sdsd","itemId":0}},
{"success":true,"commentInfo":{"uname":"shyam","comment":"dd","itemId":0}},
{"success":true,"commentInfo":{"uname":"shyam","comment":"dddf","itemId":0}}]

and the change the function to:

success: function( data, textStatus, jqXHR) 
    {
       for(var i = 0,len=data.length;i<len;i += 1){
        if(data[i].success)
        {
          //code
        }
       }
    }

on the server side just change to

out.println("[");
Boolean first = true
while(rs.next()){
        Commenter comment = new Commenter();
        comment.setUname(rs.getString("uname").trim());
        comment.setComment(rs.getString("comments").trim());
        commentObj=gson.toJsonTree(comment);
        myObj.add("commentInfo", commentObj);
        if(!first){
          out.print(",");
        } else {
          first = false;
        }
        out.println(myObj.toString());
        }   
out.println("]");
Sign up to request clarification or add additional context in comments.

2 Comments

"the trailing comma will be ignored by the JSON parser" I don't think so. jsfiddle.net/pYELD
@FelixKling well my did actually parseit :) but tryingadifferentI getthe sameresultas you
1

try this code I think It may solve Your problem :

        ArrayList<JSONObject> CommArray=new ArrayList<JSONObject>();

         while(rs.next()){
            JSONObject Obj = new JSONObject();
            Obj.put("uname",rs.getString("uname").trim());     //Adds your uname to Object
            Obj.put("comment",rs.getString("comments").trim());//Adds your comment to Object
            CommArray.add(Obj);                                //Inserts your Object to ArrayList
            System.out.println(rs.getString("comments").trim());
            }    
         JSONArray arrayObj=JSONArray.fromObject(CommArray);//Converts the Array List to JSONArray
         commentObj=gson.toJsonTree(arrayObj);   //Converts the JSONArray to Jsontree
         myObj.add("commentInfo", commentObj);   //Adds the Tree to JsonObject as commentInfo Array
         out.println(myObj.toString());        //Prints the result
         rs.close();                                                              
         stmt.close();                                                            
         stmt = null;                                                             
         conn.close();                                                            
         conn = null;                                                  

     }                                                              
     catch(Exception e){}

I hope this solves Your problem.

Comments

0

Try to temporally change the dataType and make the same bad request, output the response e let's see what's wrong.

Comments

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.