tags:

views:

85

answers:

3

I am able to send data to the server using JSON and get back the appropriate data, but before I handle the returned data appropriately I am just trying to output the returned JSON data as an alert. I cannot understand why this is not working.

I do get an alert but the text value says "undefined" - I am not sure what I need to do to either have it print the entire JSON object or one part of it.

Both System.out.println statements confirm that the correct information is coming out of the servlet.

The servlet class:

public class EditItemServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    response.setContentType("text/json");
    PrintWriter out = response.getWriter();
    String itemToEdit = request.getParameter("selectedItem");

    System.out.println(itemToEdit);

    String myString="";
    try {
        myString = new JSONObject().put("selectedItem", itemToEdit).toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(myString);
    out.print(myString);
    }
}

Here is the jQuery that sends the request and handles the response:

$("#edit-form").hide();
    $("#edit-item-btn").click(function () {
        isEditClicked = "yes";
        $("#edit-form").show();
        var editValue = $("#edit-item-select").val();
        $.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues());
        alert("wassup");
    }); 

    function displayEditValues(data) {
        alert(data);
    };  // each
+3  A: 

You need to pass the displayEditValues as a callback not invoke it displayEditValues():

$.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues);
Darin Dimitrov
+1  A: 
$.getJSON("EditItem",{"selectedItem":editValue},function(){displayEditValues()});

By this way you can pass any number of parameters to your displayEditValues() function like

function(){displayEditValues(param1, param2, ..., paramN)}
rahul
+1  A: 

Try this:

  displayEditValues = function(data) {
      alert(data);
  };
  $.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues);

Or even

  $.getJSON("EditItem", {"selectedItem" : editValue}, function(data) { alert(data); } );
MDCore