odd_duck
odd_duck

Reputation: 4111

Dynamic Post Data Values for Jquery Ajax

On my page I have multiple dropdowns like so:

<select class="form-control extra-dropdown" id="extra-1" name="extra[1]">
    <option value="0">0</option>
    <option value="1">1</option>
</select>

<select class="form-control extra-dropdown" id="extra-2" name="extra[2]">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select class="form-control extra-dropdown" id="extra-3" name="extra[3]">
    <option value="A">A</option>
    <option value="B">B</option>
</select>

These dropdowns are created dynamically - depending on where the user has come from determines what and how many dropdowns are shown.

When the user changes any of these options I want to run a php script with jQuery.ajax and it needs all the selected values for extra[]. SO it would be like so:

$('select.extra-dropdown').change(function(){
    $.ajax({
        type: 'POST',
        url: 'my-ajax-script.php',
        data: { 
            postVar1: $('#extra-1').val(), 
            postVar2: $('#extra-2').val(),
            postVar3: $('#extra-3').val()
        },
        beforeSend:function(){
            // show loader...
        },
        success:function(data){
            // show xxx...
        },
        error:function(){
            // show errors...
        }
    });
});

However how do I populate the data: {} dynicamlly based on how many dropdown options are on the page. It can vary from 1 on the page to a max of 20.

Upvotes: 0

Views: 806

Answers (1)

Hozeis
Hozeis

Reputation: 1742

Try doing this:

var dataOut = [];
$.each($('.extra-dropdown'),function(index,value){
    dataOut['extra-'+index] = $(this).val();
    //or 
    //dataOut[$(this).attr('id')] = $(this).val();       
});

Then

data : dataOut

Upvotes: 1

Related Questions