Automatic Checkbox Save w/ jQuery
While making stuff I always try to put in little short cuts to make things go faster, whether its browsing though pages or submitting forms, everything needs sped up. While making the back-end of a discussion form, I used this to save settings without having to submit a form. It just saves everything onclick :D
PHP/HTML/JS
## CONNECT TO DATABASE
$connection = mysql_connect("localhost", "username", "password");
mysql_select_db("databasename", $connection);
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://paulor.net/inc/uploads/7235checkbox.save.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('<img src="http://paulor.net/inc/uploads/3874ajax-loader.gif" id="spinner" />').css('position','absolute').hide().appendTo('body');
//for every field change
$('input#crazycheckers').click(function() {
//get element position
var position = $(this).offset();
//position image
$('#spinner').css({ top: position.top , left: position.left + $(this).width() + 30 }).fadeIn();
//ajax
$.post('<?php echo $_SERVER['REQUEST_URI']; ?>',{
ajax:1,
value: $(this).val()
},function() {
$('#spinner').fadeOut();
});
});
});
</script>
## GET CURRENT SETTINGS
$is_q = mysql_query("SELECT * FROM `settings` WHERE `id` = '1'");
$is = mysql_fetch_array($is_q);
<p><input type="checkbox" name="crazycheckers" id="crazycheckers" value="1" <?php="" if($is['checkbox']="=" 1)="" {="" echo="" '="" checked="checked" ';="" }="" ?=""> class="ajax" /></p>
<p>Refresh the page to see that its still checked/unchecked</p>
save.php
## CONNECT TO DATABASE
$connection = mysql_connect("localhost", "username", "password");
mysql_select_db("databasename", $connection);
if($_GET['checked'] == "true") {
mysql_query("UPDATE `settings` SET `checkbox` = '1' WHERE `id` = '1'");
} else {
mysql_query("UPDATE `settings` SET `checkbox` = '0' WHERE `id` = '1'");
}
The JS
$(document).ready(function(){
$('input#crazycheckers').click(function() {
$.get("save.php", { checked: $(this).attr("checked") },
function(data){
});
});
});
Simples :]
Comments