This is my first post guys, please forgive me for any glaring posting errors. I'm attempting to create a checkbox in an html page but I would like to retrieve data from my .php page. At this point in my code it doesn't matter whether the box is checked or not, it shows the same answer (that it is) - any suggestions ??
HTML code
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
//alert(xmlHttp.responseText);
document.getElementById("DisplayBox").innerHTML=xmlHttp.responseText;
}
}
// start the query string
var QueryString = "IceCream_Coating.php?";
QueryString = QueryString + "checked=" + document.getElementById("checked").value;
//alert(QueryString);
xmlHttp.open("GET", QueryString, true);
xmlHttp.send(null);
}
</script></head>
<body>
<p>Is the box Checked</p>
<form id="myform" name="myform" method="POST">
<p><input type="checkbox" name="checked" id="checked" value="yesORno"></p>
<input type="button" name="button" id="button" value="Decision" onclick="ajaxFunction();"/>
</p>
</form>
<p>
<div id="DisplayBox">
</div>
</p>
</body>
PHP code
<?php
$value = $_GET['checked'];
if (isset($value)) {
echo "Yes the box is checked.";
} else {
echo "No, the box is not checked.";
}
?>
You need to check if the checkbox is checked or not. Currently, you're just fetching the value that is set on the element, regardless if it's state.
Try this:
var QueryString = "IceCream_Coating.php?";
if (document.getElementById("checked").checked) {
// Only add the value if it is checked
QueryString += "checked=" + document.getElementById("checked").value;
}
We also need to change the PHP code:
<?php
// We need to check if the parameter is set before trying to use it
$value = isset($_GET['checked']) ? $_GET['checked'] : null;
if ($value) {
echo "Yes the box is checked.";
} else {
echo "No, the box is not checked.";
}
?>