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?

2
  • 5
    Why are you providing [] to class name? Commented Feb 22, 2014 at 5:25
  • I think might not have understood the purpose of the [] with form elements. Have a look at the PHP documentation: php.net/manual/en/faq.html.php#faq.html.arrays Commented Feb 22, 2014 at 5:32

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

3 Comments

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
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
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
0

use

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

and assign this to **attr_values** 

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

Comments

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(),

Comments

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

1 Comment

this doesn't work. it doesn't return anything