Reputation: 18514
I have a multiple select item, which allows me to check multiple items. I want to send those selected items via ajax request and afterwards I want to import the those items into my database. My problem is, that I don't know how to loop thru the passed array, which I get by the POST request.
Ajax Request
function insertPlayers(){
var data = $("#playerCards").serialize();
$.ajax({
url: "/database/playercards.php",
type: "POST",
data: data,
success: function (response) {
}
});
}
This is my HTML multiple select:
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
// Options inserted by JQuery later
</select>
This is how my data looks like when I alert it before sending the Ajax Request:
playersearch=test&buypercentage=85&assignAccount=9&assignAccount=10&assignAccount=11
How I add the options to my multiple selectbox:
// loop the response
$.each(response, function(i, e){
// just use your column names, these are just an example, but you get the idea
opt += '<option value="'+e.id+'">'+ e.email + ' - ' + e.coins + '</option>';
});
// append the markup to that select box
$('#assignAccount').html(opt)
My problem: It should be clearly now that the assignAccount variable is a array which I want to loop thru in PHP but I don't know how I can do this because I don't know the indices. This is what I've tried:
$accountIds = $_POST['assignAccount'];
foreach ($accountIds as $account){
echo $account;
}
Upvotes: 0
Views: 737
Reputation: 2522
make the select statement multiple id an array
<select name='assignAccount[]' id='assignAccount[]'>
on your php page you will now have an array for this post.
$_POST['assignAccount'][0]
$_POST['assignAccount'][1]
and so on.
Upvotes: 1
Reputation: 1661
The select element when multiple send data like this:
playersearch=test&buypercentage=85&assignAccount=9,10,11
Hence, in the PHP side you do this:
$accountIds = explode(",", $_POST['assignAccount']);
foreach ($accountIds as $account){
echo $account;
}
Upvotes: 0
Reputation: 10627
Change
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
to something more like
<select id='assignAccount' name='assignAccount[]' multiple='multiple' class='form-control select'>
Upvotes: 2