pass select value with array by ajax

2

I need to pass information from a select array to ajax but I can not. My form:

<form method="post" id="form1">
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<tr>
<td>   
<select name="sel1[]" id="sel1" onblur="run_sel(this)">
<option value="1">Valor 1</option>
<option value="2">Valor 2</option>
<option value="3">Valor 3</option>
</select>
</td>
<td><span class="tr_clone_add">+</span></td>
<td><span class="tr_clone_del">-</span></td>
</tr>
</table>
</form>
<div id="sel1_e"></div>

The jQuery:

<script>
var table = $( '#table-data' )[0]; 
$( table ).delegate( '.tr_clone_add', 'click', function () { 
    var thisRow = $( this ).closest( 'tr' )[0]; 
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '0' ); 
}); 

$(table).delegate( '.tr_clone_del', 'click', function () { 
    if($('.tr_clone').length > 1) { 
        var thisRow = $(this).closest("tr")[0]; 
        thisRow.remove(); 
    } 
});

function run_sel(sel) {     
    var text = $("#sel1").val();
        if (text != "") {
            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: { sel1: text },
            beforeSend: function() { $("#loaderdiv").show(); },
            success: function(data) { $("#loaderdiv").hide(); }
            })
            .done(function(data) {
                $("#sel1_e").html(data);
                $("#form1")[0].form.reset();
            });
        }
}
</script>
    
asked by anonymous 18.06.2018 / 15:48

1 answer

1

Serialize the form and send it through data: :

data: $("#form1").serialize(),

The value of $_POST['sel1'] in PHP will be an array with the value of each select . You can use implode() to convert string to comma-separated values:

implode(",", $_POST['sel1']);

Now, there is an error in this line:

$("#form1")[0].form.reset();

The correct one would be:

$("#form1")[0].reset();
    
18.06.2018 / 16:40