I got a table of checkboxes:
<td><input id="box" name="box" type="checkbox" value="1" checked /></td>
<td><input id="box" name="box" type="checkbox" value="2" checked /></td>
<td><input id="box" name="box" type="checkbox" value="3" checked /></td>
I want to submit checkbox value when I check or uncheck the box (each one at a time) Without refreshing the page to:
if (isset($_GET['box'])) {
echo "Success!"
}
By far I got this javascript code to check whether the box is checked or unchecked:
function validate(){
if (document.getElementById('box').checked){
alert("checked") ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
I want to add AJAX on it, but all the snippet code I try so far didn't fit good with my code. I'll thank for your help.
You want to use AJAX. Here is an example in jQuery without AJAX:
<td><input id="box1" class="box" name="box1" type="checkbox" value="1" checked /></td>
<td><input id="box2" class="box" name="box2" type="checkbox" value="2" checked /></td>
<td><input id="box3" class="box" name="box3" type="checkbox" value="3" checked /></td>
JavaScript:
$(document).ready(function() {
$('.box').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
Demo: http://jsbin.com/ipasud/1/
Now instead of doing an alert
call, do a $.post to a backend URL that takes an id and a value of checked or unchecked. For example,
$.post('/submit-checkbox.php', {id: checkbox.attr('id'), value: isChecked});
And if we put that back into the code, it would look like this:
$(document).ready(function() {
$('.box').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
$.post('/whatever-your-url-is.php', {id: checkbox.attr('id'), value: isChecked});
});
});
You can use jQuery: http://jquery.com/
<script type="text/javascript">
$(document).ready(function(){
$('#box').click(function(){
var selectedValue = $(this).value();
submitValue(selectedValue);
});
});
function submitValue(valueSelected){
var request = $.ajax({
url: URL_OF_YOUR_PHP_FILE,
type: "POST",
dataType: 'json',
data: {value: valueSelected}
});
request.done(function(results) {
//DO WHAT YOU WANT WITH YOUR RESULTS
});
}
</script>
Then in your PHP file you can get the value selected in $_POST['value'] and return what you want (in JSON format).