I have 2 select boxes in my application. Now what happens that when the user submits the page, all students that have been selected (highlighted) in select box #studentadd
gets appended to #studentselect
select box. But options which have not been selected in the first select box would not get appended to the second select box.
My question is how can I also get unselected options within '#studentadd' select box to be appended into '#studentselect' select box?
Is the issue with my php/ajax because what I do is use ajax to navigate to the seperate php file and insert the students in the #studentadd
select box into the database. But the insert only occur for those students highlighter in the #studentdd
select box. It does not perform inserts on those options where were not selected in `#studentadd'.
Below is the select box #studentadd
:
<select multiple="multiple" name="addtextarea" id="studentadd" size="10">
<option value='1'>u08743 - Joe Cann</option>
<option value='4'>u03043 - Jill Sanderson</option>
<option value='7'>u08343 - Craig Moon</option>
</select>
Below is the select box the students should be appended into:
<select id="studentselect" name="studenttextarea"></select>
Below is jquery/ajax:
function submitform() {
$.ajax({
type: "POST",
url: "updatestudentsession.php",
data: {
addtextarea:$('#studentadd').val()
},
dataType:'json', //get response as json
success: function(result){
if(result.errorflag){
//do your stuff on getting error message
var newHtml="<span style='color: red'>"+result.msg+"</span>";
$("#targetdiv").html(newHtml); //i am displaying the error msg here
$('#targetdiv').show();
}else{
//you got success message
var newHtml="<span style='color: green'>"+result.msg+"</span>";
$("#targetdiv").html(newHtml);
//append students you want to add to assessment into student exist select box
var selectedOption = $('select#studentadd');
$('select#studentselect').append(selectedOption.html());
//blank #studentadd select box
$('#studentadd').empty();
$('#targetdiv').show();
}
}
});
}
Below is the separate php file updatestudentsession.php
which gets accessed from the ajax and inserts the data into the database:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : array();
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql))
{
// Handle errors with prepare operation here
}
$success = true;
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
if($insert->execute() === false)
{
$success = false;
}
}
$insert->close();
if($success)
{
echo json_encode(array('errorflag'=>false,'msg'=>"Students have been successfully added into the Assessment"));
}
else
{
echo json_encode(array('errorflag'=>true,'msg'=>"An error has occured, Students have not been added into the Assessment"));
}