Accessing a json object gives undefined

Viewed 786

I am new to Ajax And Json. I am using Ajax for requesting the data from the java servlet and I am getting a JSON array. Now I am trying to access it but it shows undefined. I am also trying to display an image, I am getting the name of the image from the database and I am appending the path of the image with a session variable.

JSP file

<div class="search-container">
        <form id="form" name="form">
            <input type="text" id="docName" name="docSearch" placeholder="Search for any doctor by name..." style="width:30%">
            <button type="button" class="btn btn-success" id="mybtn" onclick="searchDoc()">Search</button>
        </form>
    </div>
    <br>
    <div id="img"></div>    

My Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        PrintWriter out=response.getWriter();
        HttpSession session=request.getSession(false);
        GetUserDetails details=new GetUserDetails();

        response.setContentType("application/json"); 

        String name=request.getParameter("val");
        String sql ="select fName,lName,exp,fees,user_img,username,mob,addr,email from users where fName='"+name+"'";
        String special="";
        String degree="";

        if(name==null||name.trim().equals(""))
            out.print("<p>Please enter name!</p>");
        else {
            List<Bean> docSearchList=new ArrayList<Bean>();
            try {
                con=DBConnection.createConnection();
                ps=con.prepareStatement(sql);
                rs=ps.executeQuery();
                while(rs.next()) {
                    List<String> list=details.getSpecialByUsername(rs.getString("username"));
                    special+=list.get(0);
                    for(String s:list) {
                        if(s.equals(special)) {}
                        else 
                            special+=", "+s;
                    }
                    list=details.getDegByUsername(rs.getString("username"));
                    degree+=list.get(0);
                    for(String s:list) {
                        if(s.equals(degree)) {}
                        else 
                            degree+=", "+s;
                    }
                    Bean docSearchBean=new Bean();
                    
                    docSearchBean.setfName(rs.getString("fName"));
                    docSearchBean.setlName(rs.getString("lName"));
                    docSearchBean.setExperience(rs.getString("exp"));
                    docSearchBean.setFees(rs.getString("fees"));
                    docSearchBean.setUserImage(session.getAttribute("patientSearchImage")+rs.getString("user_img"));
                    docSearchBean.setMobile(rs.getString("mob"));
                    docSearchBean.setAddress(rs.getString("addr"));
                    docSearchBean.setEmail(rs.getString("email"));
                    docSearchList.add(docSearchBean);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            Gson gson=new Gson();
            JsonElement element=gson.toJsonTree(docSearchList,new TypeToken<List<Bean>>() {}.getType());
            
            JsonArray jsonArray=element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } 
    }
}

My Js file

function searchDoc() {
    var request = new XMLHttpRequest();
    var name = document.form.docSearch.value;
    var url = "/Doctor_Appointment_Application/PatientSearch?val=" + name;
    request.open("GET", url, true);
    request.responseType = 'text';
    request.send();
    
    try {
        request.onload = function() {
        var val = request.responseText;
        var targetDiv=document.getElementById("img").innerHTML=val;

/*      var parsed=JSON.parse(val);
*/              
        var image=document.createElement("img");
        image.src=val.img;
        image.className+="img";
        
        var targetDiv=document.getElementById("img");
        targetDiv.appendChild(image);

        
/*      console.log(parsed.img);
        console.log(parsed.fName);  
        console.log(parsed.lName);  
        console.log(parsed.username);
        console.log(parsed.exp);    
        console.log(parsed.fees);   
        console.log(parsed.special);    
        console.log(parsed.degree); 

        
        var p=document.createElement("p");
        p.innerHTML=parsed.fName;

        var p1=document.createElement("p");
        p1.innerHTML=parsed.lName;

        var p2=document.createElement("p");
        p2.innerHTML=parsed.username;

        var p3=document.createElement("p");
        p3.innerHTML=parsed.exp;

        var p4=document.createElement("p");
        p4.innerHTML=parsed.fees;

        var p5=document.createElement("p");
        p5.innerHTML=parsed.special;

        var p6=document.createElement("p");
        p6.innerHTML=parsed.degree;
                
        var targetDiv=document.getElementById("img");
        targetDiv.appendChild(image);
        targetDiv.appendChild(p);
        targetDiv.appendChild(p1);
        targetDiv.appendChild(p2);
        targetDiv.appendChild(p3);
        targetDiv.appendChild(p4);
        targetDiv.appendChild(p5);
        targetDiv.appendChild(p6);
*/              
            }//end of function 
        } catch (e) {
            alert("Unable to connect to server");
    }
}

In my JS file, you can see a few comments. In my comments, I tried to parse the JSON object into js object and access it in that way but it still shows undefined. Path of the image saved in session variable:- String patientSearchImage="IMG\\";

Any suggestions would be appreciated. Thank you :)

1 Answers

I solved this error. I am going to tell you how I did it so that you can refer to this. If you have a JSON array like [{"fName":"Samanyu","lName":"Mehra"},{"fName":"Rajesh","lName":"Khanna"}]. Then you just have to do parse the JSON objects and then access it with a for loop.

var parsed=JSON.parse(val);
for(i in parsed){
    console.log(parsed[i]["fName"]);
}
Related