Ajax Jquery and Post Variables

Ajax Jquery and Post Variables

This example uses jquery to make an Ajax call via the 'POST' method. Here is how it works. When you select the checkbox, the Jquery change() function is triggered. Then, if the check box is checked, a variable = 1 is created. If it is deselected, the variable becomes = 2. Then, asyncronous ajax takes places with the proper data and url. Essentially, new post variables are created without needing to click a 'submit' button. Finally, the post variables are used to update the database table.

<?php
header('Cache-Control: no cache'); //no chache but no error
session_start();
include ("connect.inc");
$db=public_db_connect();
?>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

	$(document).ready(function(){

		$("input[name*='mycheckbox']").change(function(){
	
			var variable = $(this).attr("id");
		
			if ($(this).is(':checked')) {
		
			var variable2 = 1;
			
			} else {
			var variable2 = 2;
			
			}
						
			alert(variable);
		
			alert(variable2);
			/*var dataString = 'variable=' + variable + '&variable2=' + variable2;*/
			$.ajax({
				type: "POST",
				cache: false,
				url: "ajax-post.php",
				data: "variable="+variable +"&variable2="+variable2,
				/*data: { variable2: "variable2" },*/
				/*data: dataString,*/
				success: function(msg){
					alert("Success!");
					/*alert(variable2);*/
				}
			});
			
		});
	});
</script>
  	</head>
	<body>
	<?php
	$command = "SELECT * FROM ajax";
	$result = mysqli_query($db, $command);
	while($row = mysqli_fetch_assoc($result)){
	}

	$variable2 = $_POST['variable2'];
    $variable = $_POST['variable'];

$command = "SELECT * FROM ajax";
	$result = mysqli_query($db, $command);
	while($row = mysqli_fetch_assoc($result)){
	//echo $row['checking'];
	}

if($_POST['variable2']){
echo $variable2;
	$commandb = "UPDATE ajax SET checking='{$_POST['variable2']}' WHERE id=1";
	$resultb = mysqli_query($db, $commandb); 
	}	else{
	$commandc = "UPDATE ajax SET checking=3 WHERE id=1";
	$resultc = mysqli_query($db, $commandc) ; 
	}
	?>	
	
	<form method ="post" action = "">
<input type= "checkbox" name="mycheckbox" id="checker" value="1" />
</form>