0

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
1
  • Thanks all your solutions were helpful. Commented Jan 7, 2010 at 9:17

3 Answers 3

3

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

$.getJSON("EditItem", {"selectedItem" : editValue}, displayEditValues);
Sign up to request clarification or add additional context in comments.

Comments

1
$.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)}

Comments

1

Try this:

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

Or even

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.