pass value of select with array by ajax

Asked

Viewed 197 times

2

I need to pass the information of a select array through ajax but I’m not getting it. 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>
  • What’s the problem that’s happening?

  • 2

    There are some mistakes here: value="1'... opens with double quotes and closes with single

  • @dvd, corrected. thank you.

  • Here too: $("#form1")[0].form.reset();.. would be $("#form1")[0].reset();

  • @dvd, on the ajax.php page you only get the first selected value if you don’t use implode, with implode nothing appears.

  • From what I understand will receive the value of the option selected.

  • For name="sel1[]" it is understood that you want to send an array... but only have 1 select... how would you send an array if you only have 1 select?

  • @dvd, includes the code in the question that mounts the array, my error not having put right from the start.

Show 3 more comments

1 answer

1


Serialize the form and send by 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 to string with comma separated values:

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

Now, there’s a mistake on this line:

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

The right thing would be:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.