0

I' trying to send some data from the frontend to a Controller in Spring. I am able to recover all the data except for the Integer [] objectIds.

This is my ajax function:

           var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
           dataToSend = JSON.stringify({ 'objectIds': dataToSend });

           $.ajax({
               type:'POST',
               url:'/sendData',
               data:{'start':start, 'end':end, 'locale':locale, dataToSend},
               async:false,
               dataType: "json",
               success:function(data){}
           });

And this is my Controller function:

    @PostMapping(path="/sendData")
public @ResponseBody String sendData(HttpServletResponse response, 
        @RequestParam(required=true, name="start") String start, 
        @RequestParam(required=true, name="end") String end,
        @RequestParam(required=true, name="locale") Locale locale,
        @RequestParam(required=false, name="objectIds") Integer[] objectIds) throws DocumentException, IOException {

    //some more code
}

any idea why it's not working??

0

2 Answers 2

1

Problem is in the way you are sending JSON

Case 1: How you are sending

 var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });

var mainJSOn = {
    'start': "start",
    'end': "end",
    'locale': "locale",
    dataToSend
  }
  console.log(JSON.stringify(mainJSOn));

OUTPUT:

   {"start":"start","end":"end","locale":"locale","dataToSend":"{\"objectIds\":[{\"objectIds\":111},{\"objectIds\":222}]}"}

Case 2: How you should actually send

    var dataToSend1 = [{ objectIds: 111 }, { objectIds: 222 }];
    dataToSend1 = JSON.stringify(dataToSend1 );

    var mainJSOn1 = {
        'start': "start",
        'end': "end",
        'locale': "locale",
        'objectIds': dataToSend1
      }



  console.log(JSON.stringify(mainJSOn1));

OUTPUT:

{"start":"start","end":"end","locale":"locale","objectIds":"[{\"objectIds\":111},{\"objectIds\":222}]"}

Look at the Output of Both Cases.

Change your code like done in Case 2

Working Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ashish Kumar I was definitely forming the json in an erroneous way
0

Your are stringifying the wrong object and burying the key objectIds inside it

Try changing to

var dataToSend = JSON.stringify([{objectIds: 111}, {objectIds: 222}]);    

$.ajax({
  type: 'POST',
  url: '/sendData',
  data: {
    'start': start,
    'end': end,
    'locale': locale,
    'objectIds': dataToSend
  },
  // async:false,  // NEVER USE THIS!!!!
  dataType: "json",
  success: function(data) {}
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.