Lowb
Lowb

Reputation: 172

Convert form results to array with jQuery or other

I'm trying to get a form result to an array so it can be handled by the next JSP page.

Currently I have this code:

$("seguimiento").submit(function(){
        var labels = new Array();
        var val = new Array();
        $(":input").each(function(){
           if ($(this).val() >0) {
              labels.push($(this).attr('name'));
              val.push($(this).val());
           }
        });
        console.log("ya hemos rellenado los arrays");
       $.post("enviar.jsp", {"etiquetas": labels.join(','), "valores": val.join(',')});
     });

But it is just not working at all, I don't even get on the console the debugging message.

Of course my form has name="seguimiento"

Upvotes: 1

Views: 205

Answers (2)

Bluemagica
Bluemagica

Reputation: 5158

simply serialize() or serializeArray()

$.post("enviar.jsp",$("form").serialize(),function(d){});

To get the console msg

$("form[name='seguimiento']").submit(function(e){
        e.preventDefault();
        var values = $(this).serializeArray();//this contains the array you want
        console.log(values);
        $.post('enviar.jsp',values,function(d){
             //d is the output of enviar.jsp
             console.log(d);
        });
     });

Depending on the data, you can consider using window.location to redirect to enviar.jsp and send the data as url variables.

Upvotes: 3

Adil
Adil

Reputation: 148140

You can not pass arrays of javascript, Instead of sending array pass comma separated strings, you can use join to make comma separated string from array.

Change

$.post("enviar.jsp", {etiquetas: labels, valores: val});

To

$.post("enviar.jsp", {"etiquetas": labels.join(','), "valores": val.join(',')});

Upvotes: 2

Related Questions