Having a problem with simple AJAX call that checks if checkbox is checked. At the moment, no matter if the checkbox is checked or not, it would print "not checked". I've tried changing "POST"/"GET" methods in he PHP code, but the result is same, i dont know why? any ideas?thanks!
#test.html
<html>
<head>
<script type="text/javascript">
function load()
{
var xmlhttp;
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("div1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","checkbox.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="checkbox" value="value1" name="check1"/>BOX 1</input>
<br>
<input type="checkbox" value="value2" name="check2">BOX 2</input>
<br>
<button type="button" onclick="load()">Run</button>
<div id="div1"></div>
</body>
</html>
#checkbox.php
<?php
if(isset($_GET['check1'])
{
echo "checked";
}
else
{
echo "not checked";
}
?>
I don't see the point of using AJAX for this, can't you just check in javascript if the checkbox is checked or not ?
Anyhow I'm more used to jQuery but it doesn't seem that you are sending any data, you need to test if the checkbox is checked in javascript and send the result in your request.
You don't actually send any values to checkbox.php
when making the AJAX request, so $_GET['check1']
will never have a value. Thus the else
block is always reached.
Inside your load()
function you need to determine the current state of the checkboxes and send that state to the server in the AJAX request. Something like this might be able to determine that state:
var checkedBox = '';
if (document.getElementsByName('check1')[0].checked) {
checkedBox = 'check1';
} else if (document.getElementsByName('check2')[0].checked) {
checkedBox = 'check2';
}
So checkedBox
would hold the name of the first checkbox that's currently checked (kind of assuming radio button functionality here, but you can tweak as needed for whatever you're trying to accomplish), or an empty value if nothing is checked.
Then you can use that in a URL value:
var ajaxUrl = 'checkbox.php';
if (checkedBox !== '') {
ajaxUrl += '?' + checkedBox + '=true';
}
So, for example, if check1
is checked then the resulting ajaxUrl
value would be:
checkbox.php?check1=true
If nothing is checked, it would just be:
checkbox.php
Then use that URL in your AJAX request:
xmlhttp.open('GET', ajaxUrl, true);
This can all be refactored and simplified I'm sure, but I tried to break it out into logical steps that you can observe and learn from. It's definitely also worth stating that you don't even need to use AJAX for this, since you can just determine the state of the checkboxes and display a message entirely client-side. I'm guessing you're doing this as a learning exercise for AJAX, though.