0

I want to send a json with Ajax to the Spring MVC controller but I can not get anything, I do not know what I'm failing

Javascript:

   var search = {
      "pName" : "bhanu",
      "lName" :"prasad"
   }

   var enviar=JSON.stringify(search);

    $.ajax({
      type: "POST",
      contentType : 'application/json; charset=utf-8',
      url: 'http://localhost:8080/HelloSpringMVC/j',
      data: enviar, // Note it is important
      success :function(result) {
       // do what ever you want with data
     }
  });

Spring MVC:

@RequestMapping(value ="/j", method = RequestMethod.POST)
     public void posted(@RequestBody Search search) {
         System.out.println("Post");
         System.out.println(search.toString());
     }
dimitrisli
  • 20,895
  • 12
  • 59
  • 63
sgm
  • 103
  • 1
  • 6
  • What does the `Search` class look like? I'm pretty sure from this example you are not wanting to send json, but rather a query string in the body. The mvc should try to match the keys in the query string to the elements in the Search class. At minimum, from this example, the Search class should contain two `String` variables; `pName` and `lName` – Taplar Mar 27 '18 at 21:02
  • please use `JSON.parse` instated of `JSON.stringify` – Divyesh Kanzariya Mar 28 '18 at 06:00
  • Esta es mi clase de búsqueda: public class Search { private String pName; private String lName;} – sgm Mar 29 '18 at 09:20
  • When you parse data to either GET or POST the data should be URL encoded before transmission, this will escape any characters that would otherwise break the protocol. – SPlatten Aug 23 '19 at 06:55

3 Answers3

0

Haven't used Spring MVC, but i can say one thing. When you add the header

contentType : 'application/json; charset=utf-8',

the data wont be retrieved in the same way a normal POST request will be handled. Try removing that header and check the difference.

In addition, don't 'stringify' the data. jQuery AJAX function expects a object for property 'data'.

0

I think you made things complicated,in fact,if you have a Search object defined,you can past the data directly to the Controller method,and SpringMVC will form an instance of the search object for you,try as below:

var search = {
      pName : "bhanu",
      lName :"prasad"
};

$.ajax({
  type: "POST",
  url: 'j',//do not put the full url,you need use an absolute url
  data: search,//put search js object directly here
  success :function(result) {
   // do what ever you want with data
 }

Now you can get the search object as below:

 @RequestMapping(value ="/j", method = RequestMethod.POST)
 public void posted(Search search) {
     System.out.println("Post");
     System.out.println(search.toString());
 }
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • thanks, but now I call but I have shown the values ​​to check and they appear as null @RequestMapping(value ="/j", method = RequestMethod.POST) public void posted (Search search) { System.out.println("vieho "); System.out.println(search.toString()); String i= search.lName; System.out.println(""+i); } – sgm Mar 30 '18 at 09:37
  • do you have the getter and setter method in `Search` class? can you show me the code? – flyingfox Mar 30 '18 at 09:39
  • also,please change the url in the ajax request – flyingfox Mar 30 '18 at 09:40
  • Yes, this is my Search class: public class Search { String pName; String lName; public String getpName() { return pName; } public void setpName(String pName) { this.pName = pName; } public String getlName() { return lName; } public void setlName(String lName) { this.lName = lName; } } – sgm Mar 30 '18 at 09:41
  • is your search object null or have empty value now?I just updated my answer – flyingfox Mar 30 '18 at 09:48
  • @lucumt in this way, the passing object comes as null even though the data is bound –  Apr 05 '20 at 12:14
-1
var fullName = $("#fullName").val();
var location = $("#location").val();
var capacity = $("#capacity").val();
var guarantee = $("#guarantee").val();
var status = $("#status").val();
var data = {
    name : fullName,
    capacity : capacity,
    guarantee : guarantee,
    location : location,
    status : status
}
var uri = $("#contextpath").val()+"/rooms/persist?inputParam="+encodeURIComponent(data);
data = JSON.stringify(data);
$.ajax({
    url : uri,
    type : 'POST',
    dataType : 'json',
    success: function(data){
        var successflag = data.response.successflag;
        var errors = data.response.errors;
        var results = data.response.result;
        if(successflag == "true"){
            $("#fullName").val("");
            $("#location").val("");
            $("#capacity").val("");
            $("#guarantee").val("");
            $("#status").val("");
        }else{

        }
    },
    error: function (xhr, ajaxOptions, thrownError) {

    }
});



public static org.json.simple.JSONObject getInputParams(String inputParams) {
        JSONParser parser = new JSONParser(); 
        org.json.simple.JSONObject inputJSON = new org.json.simple.JSONObject();
        try {
            inputJSON = (org.json.simple.JSONObject) parser.parse(inputParams);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    return inputJSON;
}


@RequestMapping(value = "/persist", method = RequestMethod.POST)
    public @ResponseBody String add(Model model, HttpServletRequest request) {
        try {
                JSONObject inputJSON = CommonWebUtil.getInputParams(request.getParameter("inputParam").toString());
                if (inputJSON != null){
                    if(inputJSON.get(CommonConstants.NAME) != null && !inputJSON.get(CommonConstants.NAME).toString().isEmpty()){

                    } 
                    if(inputJSON.get(CommonConstants.CAPACITY) != null && !inputJSON.get(CommonConstants.CAPACITY).toString().isEmpty()){
                    } 
                    if(inputJSON.get(CommonConstants.GUARANTEE) != null && !inputJSON.get(CommonConstants.GUARANTEE).toString().isEmpty()){
                    } 
                    if(inputJSON.get(CommonConstants.LOCATION) != null && !inputJSON.get(CommonConstants.LOCATION).toString().isEmpty()){
                    } 
                    if(inputJSON.get(CommonConstants.STATUS) != null && !inputJSON.get(CommonConstants.STATUS).toString().isEmpty()){
                    }
                }
        }catch (Exception e) {

        }
    }
Java
  • 1