Reputation: 988
I have some checkbox values that I generate as
$sql = "sql statement";
$courseResult = mysqli_query($connection, $sql);
$courses = mysqli_fetch_row($
// Display the courses the user has taken
while ($courses) {
echo "<td><input type='checkbox' name='coursesToAdd[]' id='coursesToAdd[]' value='$courses[0]'>$courses[0]</td></tr>";
$courses = mysqli_fetch_row($courseResult);
}
<input type='button' onclick='EditStudentCertificates()' value='Submit'/>
what i want to do is get the values that the user checks into an array, and than access this array from javascript which i was trying to do as such, but it does not seem to work:
function EditStudentCertificates(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var coursesToAddField = document.getElementById("coursesToAdd[]");
var coursesToAdd = coursesToAddField ? coursesToAddField.value : '';
xmlhttp.open("POST","updateStudentCInfo.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("certValue="+certValue+"&coursesToAdd="+coursesToAdd);
window.alert("Your certificate information has been updated");
window.location.reload();
}
What i think the problem is is something with the way i trying to get the values from the checkboxs in the javascript, possibly something with:
var coursesToAddField = document.getElementById("coursesToAdd[]");
var coursesToAdd = coursesToAddField ? coursesToAddField.value : '';
Because the variable coursesToAdd doesnt seem to hold anything but the value of the first checkbox on the page no matter how many checkboxes i check on the page before hitting submit.
Upvotes: 0
Views: 1695
Reputation: 8640
As I mentioned in my comment above:
Without even looking at the AJAX code you posted, you are having a problem with the way you get the values from the checkboxes. You are using the same id coursesToAdd[]
to all checkboxes. That is invalid, as all ids need to be unique on the page. You need to use a classname instead.
In your HTML/PHP:
while ($courses) {
echo "<td><input type='checkbox' name='coursesToAdd[]' class='coursesToAdd' value='$courses[0]'>$courses[0]</td></tr>";
}
And in your JS you can get to the checkboxes like this:
var courseCheckboxes = document.getElementsByClassName("coursesToAdd");
for (var i=0; i < courseCheckboxes.length; i++) {
if (courseCheckboxes[i].checked) {
// do something with the checkbox
}
}
Upvotes: 1
Reputation: 2057
When having more than one values to pass through POST it requires encodeURIComponent(variablename)
Upvotes: 0
Reputation: 12683
You are doing it async. So you should make use of onreadystatechange event.
Try:
xmlhttp.onreadystatechange = function(){
window.location.reload();
}
And remove the location.reload()
Upvotes: 0