Funereal
Funereal

Reputation: 673

Ajax send JSON array to servlet

I made a table that sums rows and columns of a table. But now I want to calculate the sum in Servlet.I'm sending the array of columns and rows with JSON to Servlet. Everything works ok. But the problem now is, How can I calculate the sum of rows and columns in servlet and send back?

This is my code:

  $(document).on('change',function(){

     var columnValues={}, rowValues={};

     $("#sum_table tr").each(function(rowIndex){
          $("td input", $(this)).each(function(colIndex){
            var value=$(this).val();
            // indexes need +1 to get the row number, because 
            // the indexes are 0-based.
            if (undefined===columnValues[colIndex+1]){
              columnValues[colIndex+1]=[];
            }
            if (undefined===rowValues[rowIndex+1]){
              rowValues[rowIndex+1]=[];
            }
            rowValues[rowIndex+1].push(value);
            columnValues[colIndex+1].push(value);

          });

      });
            // send data to server
       $.ajax({
           url: 'ServletPost',
           type: 'post',
           data: {rows:rowValues, columns:columnValues},
           dataType: 'json',
           success: function(data){
               // insert your server-calculated data to dom   
               var rows = data.rows,
                columns = data.columns;

                // insert your server-calculated data to dom   
                $("td.total").each(function(rowIndex){
                    $(this).text(rows[rowIndex+1]);
                });

                $("tr.totalCol td").each(function(columnIndex){
                    $(this).text(columns[columnIndex+1]);
                });
           }
       }); 
});

Thank You in Advance!

Upvotes: 0

Views: 4260

Answers (1)

SeeTheC
SeeTheC

Reputation: 1631

I will not tell exact solution but a way.

0>

$.ajax({
        url:"ServletPost",
        type:"POST",
        dataType:'json',
        data: {rows:rowValues, columns:columnValues},
        success:function(data){
            // codes....
        }

    });

1> In doPost() function in servlet

 String[] rows= request.getParameterValues("rows[]");
 String[] columns= request.getParameterValues("columns[]");

2> Find sum.

3> Return the Json Result

response.setContentType("application/json");
PrintWriter out = response.getWriter();
String jsonStr = "{\"rows\": \""+rowsResult+"\",\"columns\":\""+columnsResult+"\"}";
out.print(jsonStr);
out.flush();

Upvotes: 1

Related Questions