0

I am trying to pass an array of JS objects with 5 variables in the in the object. When trying to get the array of objects in the java servlet I keep getting a NULL. Passing a single variable or an object of variables works perfectly.

Java Servlet:

String [] s = req.getParameterValues("json[]");

I have also tried

String [] s = req.getParameterValues("json");

I added the [] because of this answer.

JavaScript code:

var list = [];
$(x).each(function(index, e) {
    var y = $(e).find("input[id*='numOfShares']");
    var id = y.attr('name');
    var num = y.val();
    var price = y.val();
    var date = y.val();
    var symbol = $("#holdSymb").val();

    var hold = {
            "holdingsID" : id, 
            "symbol" : symbol, 
            "purchasePrice" : price, 
            "numberOfShares" : num, 
            "purchaseDate" : date
    };

    list.push(hold);
});



$.ajax({
    url:"URL",
    type:"POST",
    dataType:'json',
    data: {json:list},//Also tried {'json':list},
    success:function(data){
        console.log("Done");
    },
    fail:function(data) {
        console.log("Failed");
    }
});
Community
  • 1
  • 1
develop1
  • 747
  • 1
  • 10
  • 32
  • Your server side code looks ok, no need to add `[]`. Can you check the value of `list` before making the call, put it on an `alert(list)`? See if the list is populated before making the `ajax` call. – ahoxha Mar 24 '17 at 18:35
  • @ahoxha Yes it displays data. – develop1 Mar 24 '17 at 18:40
  • try adding another parameter to `data`, for example: `data: {json:list, test:"test"}`, then try to get the value of that parameter `req.getParameter("test");`. Just to make sure that parameters are getting passed to the server. – ahoxha Mar 24 '17 at 18:48
  • Yes It does work. – develop1 Mar 24 '17 at 18:55
  • Send it as JSON and parse it as JSON in the servlet. – DwB Mar 24 '17 at 18:59
  • Try this: `data: {json:JSON.stringify(list)}`, on the server side `req.getParameter("json");`. – ahoxha Mar 24 '17 at 19:01

0 Answers0