Java Curious ღ
Java Curious ღ

Reputation: 3692

How to send JavaScript array to Servlet inside form tag?

I have made checkbox code and on checkbox click I am calling function which will add passed argument to JavaScript array. I have taken form tag inside body and inside form tag there is only checkboxes and a button. On button click servlet will called so I want some mechanism that will also send Java Script array data to servlet with checkbox value.

onClick of checkbox I am not passing checkbox value, I am passing other details so need other function to add data in array and pass it to servlet.

checkbox code :

<input type="checkbox" id="demo_box_2<%= aname %><%= aval %><%=k %>" class="css-checkbox" name="configcheckbox" value="<%= aval %>" onchange="addcategory('<%= acid %>')">
<label for="demo_box_2<%= aname %><%= aval %><%=k %>" name="demo_lbl_2<%=k %>" class="css-label">&nbsp;<%= aval %></label>

JavaScript function :

            var acdata = [];
            function addcategory(acid)
            {
                    acdata.push(acid);
                    //alert(acid);
            }

the code of checkbox is inside form tag, so I also want to send acdata[] array with checkbox value to servlet, so any help please ?

Upvotes: 0

Views: 4220

Answers (2)

Vinoth Krishnan
Vinoth Krishnan

Reputation: 2949

Here is sample code as Santosh explained,

In your script (Edited),

var acdata = [];
function addcategory(acid)
{
    acdata.push(acid);
    $("#hidden_array").val(acdata);
}

In your html,

<input type="checkbox" id="demo_box_2<%= aname %><%= aval %><%=k %>" 
class="css-checkbox" 
name="configcheckbox" value="<%= aval %>" onchange="addcategory('<%= acid %>')">
<label for="demo_box_2<%= aname %><%= aval %><%=k %>" name="demo_lbl_2<%=k %>" 
class="css-label">&nbsp;<%= aval %></label>

With this add one more hidden field inside your form like this,

<input type="hidden" id="hidden_array" name="hiddenArray" >

Hence you can get the array values in your jsp/servlet like this,

request.getParameterValues("hiddenArray");

PS: You can use string array String[] to process your data.

Upvotes: 1

Santosh
Santosh

Reputation: 17893

Here is one way to achieve this,

  1. Create a hidden field inside the form,
  2. Convert Javascript array to a comma/pipe separated string, (example 1, 2)
  3. Set the value of the hidden field to this string, (example here)
  4. This way, when you submit the form, the hidden field data is also sent to server,
  5. On the server side, split the string to get the data back as array of Java strings.

Upvotes: 0

Related Questions