0

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.

1 Answer 1

1

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

2 Comments

Thank you that works. What would I use to get the extras in my php script? (for example I want to access them in a loop liek so: foreach ($_POST['extra'] as $id => $value) { ...}
if im not mistaken you could always just send the array and traverse it in php. try data : { 'extraArray' : dataOut} then in php do foreach ($_POST['extraArray']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.