0

I am trying to parse json data returned from my servlet in JavaScript with JQuery, Here is JavaScript:

$(document).ready(function(){
//alert('document ready');
$('#search-btn').click(function(){
//  alert($('#searchbar').val());
    var url= 'http://localhost:8080/SMDE/Search?q='+$('#searchbar').val();
    //alert(url);
    var table='';
    $.get(url,function(response){
        //alert(response);
        if(response){
            //alert(response);
            $('#container').html(response);
            for(i=0;i<response.data.length;i++){
                var n= response.data[i].name;
                var c= reponse.data[i].category;
                var ii=response.data[i].id;
                table=table+"<div class='content'>" +
                        "<h3>Page Name :" +n+"<br/>"
                        "Category :" +c+"<br/>"
                        "</h3>" +
                        "<form action='/Profile' method='POST'>" +
                        "<input type='hidden' name='id' value='" +ii+
                        "'<input type='submit' class='btn' value='More...' /></form></div>";
            }
            $('#container').html(table);
        }
        if (response.error) {
              alert('Error - ' + response.error.message);
              //return
        } 
    });
}); });

When i uncomment alert(response); i get correct response, but if i alert(response.data) it says undefined. The result when url is directly given in browser is:

{ "data": [
{
  "category": "Media\/news\/publishing",
  "name": "CNN",
  "id": "5550296508"
},
{
  "category": "Media\/news\/publishing",
  "name": "CNN International",
  "id": "18793419640"
},
{
  "category": "Tv show",
  "name": "CNN Heroes",
  "id": "86418982488"
},
{
  "category": "Tv network",
  "name": "CNN en Espa\u00f1ol",
  "id": "89613772643"
},
{
  "category": "Media\/news\/publishing",
  "name": "CNNMoney",
  "id": "6651543066"
},
{
  "category": "News\/media website",
  "name": "CNNM\u00e9xico",
  "id": "323626813995"
}] }

Please help with processing data.

The servlet code is:

    import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.*;

/**
 * Servlet implementation class Search
 */
@SuppressWarnings("unused")
@WebServlet("/Search")
public class Search extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Search() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String key = request.getParameter("q");
        PrintWriter out = response.getWriter();
        String result = Facebook.callGet("search?q="+key+"&type=page");
        try{
            /*JSONObject json = new JSONObject(result);
            response.setContentType("application/json");
            out.print(json);*/
            out.println(result);
        }catch(Exception e){
            out.println("error");
        }
    }

}

3 Answers3

0

You need to set the response content type in order to hint jQuery how to interpret the response body. In case of JSON, you need to set the response content type to application/json:

response.setContentType("application/json");

This way you don't need to hack around with ugly and security/error-prone workarounds like eval() as suggested in the other answer.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

It looks like you have a problem with the $.get() method. The method works asynchronously, hence the data received is undefined when you read it. The alert statement adds delay to the whole process. That is why you are getting the data when the statement is uncommented.

  • Use $.post
  • Set the property async:false (makes it synchronous)
  • Or put the UI rendering logic in the call back success function
Aby Rajan
  • 21
  • 7
-1

$.get reads in the raw response data. response is a plain string, no json at this point.

 $.get(url,function(response){
        var d = eval("("+response+")");
        alert(d.data);

Additionaly there is no closing ] in your data.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111