Något som leder dig in på en snyggare väg:
// $_POST is way cooler than $_REQUEST
if (isset($_POST['gender']) && !empty($_POST['gender'])) {
// sql injection sucks
$gender = my_real_escape_string($_POST['gender']);
// cast it as an integer, sql inject impossible
$id = intval($_GET['id']);
if($id) {
// spit out the boolean INSERT result for use by client side JS
if(mysql_query("UPDATE users SET gender=$gender WHERE id=$id")) {
echo '1';
exit;
} else {
echo '0';
exit;
}
}
}
Om vi antar samma uppmärkning, en ajaxy-lösning (med jQuery ):
<script>
var id = <?=$id?>;
// when the DOM is ready
$(document).ready(function() {
// 'click' because IE likes to choke on 'change'
$('input[name=gender]').click(function(e) {
// prevent normal, boring, tedious form submission
e.preventDefault();
// send it to the server out-of-band with XHR
$.post('save.php?id=' + id, function() {
data: $(this).val(),
success: function(resp) {
if(resp == '1') {
alert('Saved successfully');
} else {
alert('Oops, something went wrong!');
}
}
});
});
});
</script>