ndAR
ndAR

Reputation: 371

serialize array inputs and send it via post jQuery

I'm trying to format the data to send it to the server via ajax but I can't serialize exactly the inputs to get the correct array at the end, I cannot understand what I'm doing wrong.

<input name="option[16]" value="Value1">
<input name="option[17]" value="Value2">
<input name="option[18]" value="Value3">

var final_options = new Array();
$('input[name="option[]"]').each(function() {
    final_options[$(this).attr('name')] = $(this).attr('value');
});
$.ajax({
    type: "POST",
    url:"./urlPost",    
    data: {final_options: final_options},
    dataType: 'json',
    success: function(data){
        console.log('Ok');
    }
});

On server side I need to translate it as;

array(
  array(
    '16' => 'Value1'
  ),
  array(
    '17' => 'Value2'
  ),
  array(
    '18' => 'Value3'
  ),
)

Upvotes: 0

Views: 46

Answers (1)

Barmar
Barmar

Reputation: 780714

Use .serialize. You don't need a form, you can select the elements themselves.

var final_options = $("input[name^=option]").serialize();

Note that I used an Attribute Starts With Selector to match all the option[#] inputs. Your selector would only match name=option[], not name=option[16].

On the server this will become:

$_POST['final_options'] = array(
    'options' => array(
        16 => 'Value1',
        17 => 'Value2',
        18 => 'Value3'
    )
)

In your code, $(this).attr('name') will be something like option[16]. So when you do

final_options[$(this).attr('name')] = $(this).attr('value');

you're assigning to final_options['option[16]'], not final_options[16].

Finally, to get the current value of an input, use .val(), not .attr('value'). The latter gets the value attribute from the DOM, which is just the initial default value.

Upvotes: 1

Related Questions