SandyKrish
SandyKrish

Reputation: 232

How to send Javascript multidimensional array values to Java servlet?

I have store the textbox's value to the multidimensional array in Javascript named as records (below code) and I need to send these array object to my servlet page. But I have no idea about how to get the complete array data.

Javascript code

function insert(row,col){   
var r = row, c=col; 
var q = new Array(); 
for(i=0; i<r; i++){
    q[i] = new Array(); 
    for(j=0; j<c; j++){
    var pick = "#"+i+j;  // select the id's of textbox 
    q[i][j] = $(pick).val(); // store the textbox value to array
    }
  }
 $.ajax({
    url: 'Insert',
    type: 'post',
    data: {records : q, row: r,field: c },   // need to send the records array
    success: function(result){
        console.log(result);
    }
 });
}

Java code

protected void doGet(HttpServletRequest request, HttpServletResponse 
 response) throws ServletException, IOException {

 PrintWriter out = response.getWriter();
// need to get the javascript array. but HOW ? 
}

Upvotes: 0

Views: 524

Answers (1)

Asons
Asons

Reputation: 87303

You can't send an object like that using Ajax, use JSON.stringify() to create a JSON string, e.g.

data: JSON.stringify({records : q, row: r,field: c }),

And as commented, decide which HTTP method to use, as if Ajax is of type post the servlet won't catch it with a doGet.


Updated

Here is a good answer, showing a doPost in more detail

Upvotes: 1

Related Questions