1

I have the following in a form

<input type="text" class="attr_values[]" value="1" /> <input type="text" class="attr_values[]" value="2" />

And I am trying to pass all the values in the "attr_values" array so it can be posted via Ajax but the following doesn't work.

$.ajax({   
   url: 'index.php',
   type: 'POST',
   data:{ 
      attr_values: $('.attr_values').val()

How can this be done?

4 Answers4

1

First you have to set name attribute for all input elements and remove [] from class attribute, which is absolutely wrong uses of classes:

<input type="text" name="attr_values[]" class="attr_values" value="1" />
<input type="text" name="attr_values[]" class="attr_values" value="2" />

Then, serialize input values using jQuery as:

var __data = $('input[name^="attr_values"]').serialize();
// Or if input has parent form
var __data = $('#form-id').serialize();

$.ajax({
    url: 'index.php',
    type: 'POST',
    data: __data
Vin.AI
  • 2,369
  • 2
  • 19
  • 40
  • I had tried with name=attr_values[] but I guess I was forgetting about the input[name=] in jquery.. but using this I get: attr_values%5B%5D=1&attr_values%5B%5D=2 and I want in fact only 1,2 –  Feb 22 '14 at 07:10
  • So, you can comma separate values: `var e = $('input[name^="attr_values"]'); var v=new Array(e.length); e.each(function(i,j){ v[i]=j.value; }); v.join(",");` OR do `implode(',', $_POST['attr_values'])` on server side – Vin.AI Feb 22 '14 at 07:23
  • By doing this it worked `var attrs = new Array(); $('input[name^="attr_values"]').each(function() { attrs.push($(this).val()); }); var attrs_combined = attrs.join(); $.ajax({ url: 'index.php', type: 'POST', data: attrs_combined ` –  Feb 22 '14 at 07:31
0

use

var = $( '#your_form_id_or_class' ).serialize() ;

and assign this to **attr_values** 

ref : https://api.jquery.com/serialize/

Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
0

You would have to use a wildcard selector:

$('input[name^="attr_values"]').serialize();

The selector above will find every <input> who's name starts with attr_values and serialize it for you so you would simply do:

data: $('input[name^="attr_values"]').serialize(),
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

You may not need [] in for your input element class name

<input type="text" class="attr_values" value="1" />
<input type="text" class="attr_values" value="2" />

You don't need to use serialize jQuery API

If value passes to the data parameter of jQuery.ajax is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.

var attrValueArray = $("input.attr_values").map(function(){
  return this.value;
}).get();

$.ajax({   
   url: 'index.php',
   type: 'POST',
   data:{ 
      attr_values: attrValueArray
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236