I have a HTML form (PHP), that has one or two checkboxes depending on what a user selects in a dropdown earlier in the form. The problem is:
When a user selects an option from the dropdown, I need to access an SQL DB to find out how many records fit the query and if it exceeds a limit, only allow one checkbox, otherwise 2.
Pseudo:
Select location dropdown (populated by PHP/SQL );
If onchange.location has less than 50 records
show/enable 2 type checkboxes
else
show/enable one type checkbox
From the research I've done:
Using javascript to access server DB is a no-no,Can't be done on client side using PHP.When a user selects a user in the dropdown list, a function showUser()
is triggered by the onchange
event.
HTML Page:
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
AJAX request sent to getuser.php
, so you can do request to your DB.
Code of getuser.php
:
<?php
$q = intval($_GET['q']); // your sent parameter by AJAX
// do your request and process all needed info from DB.
?php>
You can find all needed info in this tutorial.