Bluemagica
Bluemagica

Reputation: 5158

How to send array values in a $.get call via jquery?

Let's say I have multiple text boxes with array names, like:

<input type='text' name='test[]' class='test_tb' id='test1' value=''/>
<input type='text' name='test[]' class='test_tb' id='test2' value=''/>

Now if I was using a form, I could easily serialize it and send it, but I want to know how to build it manually. I tried something like

$.get('test.php',{
   'test[]':$("#test1").val(),
   'test[]':$("#test2").val()
},function(d){
   console.log(d);
});

But since a object can't have repeating keys, obviously this didn't work...so what is the manual way of doing this?

PS: This is for learning purpose not any actual task.

Upvotes: 0

Views: 60

Answers (3)

Biggie Mac
Biggie Mac

Reputation: 1357

I think Jquery's map is the solution in this case. For a more generic solution, I would recommend using the following approach:

var values = $("input[type='text']")
          .map(function(){return $(this).val();}).get();

$.get('test.php', {
   test: values
}, function(d){
   console.log(d);
});

Upvotes: 1

Radosław Miernik
Radosław Miernik

Reputation: 4094

You want array, so make array.

$.get('test.php', {
   test: [
     $("#test1").val(),
     $("#test2").val()
   ]
}, function(d){
   console.log(d);
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

Try

$.get('test.php',{
   'test[]':[$("#test1").val(), $("#test2").val()]
},function(d){
   console.log(d);
});

Upvotes: 1

Related Questions