pdm pdm - 2 months ago 6
Ajax Question

How to display JSON data in jquery dialog

I have an ajax call that sends data to a controller. The controller returns a JSON object containing a user object. In my success function I want to open a dialog and display the user's information in the dialog.



$.ajax({
type: "get",
url: $(".user-details-link").attr("href"),
dataType: "json",
cache: true,
error: function(jqXHr,textStatus, errorThrown) {
alert("Error opening dialog:\n" + errorThrown);
},
success: function(data){
$("#view-user").removeClass("hidden");
$("#view-user").dialog(dialogOpts);
$("#view-user").dialog("open");

}

});//end ajax





This is the code that returns the json object

@RequestMapping(value="/admin/user/detail", method=RequestMethod.GET)
public @ResponseBody void userDetail(HttpServletRequest request,
HttpServletResponse response, @RequestParam("id") int id)
throws IOException, JSONException, ServletException{
MMUser user = iUserService.getUser(id);
JSONObject jsonObject = new JSONObject();

jsonObject.put("user", user);

response.setContentType("application/json");
response.getWriter().println(jsonObject);
}


I am fairly new to spring so please bear with me.
The code is working fine. I am successfully returning a json object back to JavaScript. I'm struggling with this part; I want to display the user's details in the #view-user div. #view-user div is displayed inside a dialog. The dialog is also working but it's empty because i don't know how to display the information inside it. Is there a way to use the json object from the server to display my data like this in the dialog?



<div id="view-user">
<table>
<tr>
<td>
${user.getEmail()}
</td>
<td>
${user.getFirstName()}
</td>
<td>
${user.getLastName()}
</td>
</tr>
</table>
</div>




Answer

Controller

@RequestMapping(value="/admin/user/detail", method=RequestMethod.GET)
public @ResponseBody MMUser userDetail(HttpServletRequest request, 
    HttpServletResponse response, @RequestParam("id") int id)
            throws IOException, JSONException, ServletException{
   MMUser user = iUserService.getUser(id);
   return user;
}

JS

$.ajax({
    type: "get",
    url: $(".user-details-link").attr("href"),
    dataType: "json",
    cache: true,
    error: function(jqXHr,textStatus, errorThrown) {
             alert("Error opening dialog:\n" + errorThrown);
    },
    success: function(data){                    
        $("#email").val(data.email);
        $("#firstName").val(data.firstName);
        $("#lastName").val(data.lastName);
        $("#view-user").removeClass("hidden");
        $("#view-user").dialog(dialogOpts);
        $("#view-user").dialog("open");

    }

});//end ajax

HTML

<div id="view-user">
<table>
 <tr>
   <td>
     <span id="email"></span>
   </td>
   <td>
    <span id="firstName" ></span>
  </td>
  <td>
    <span id="lastName"></span>
  </td>
</tr>