Skip to content

Instantly share code, notes, and snippets.

@davidbody
Created March 22, 2011 01:14
Show Gist options
  • Save davidbody/880578 to your computer and use it in GitHub Desktop.
Save davidbody/880578 to your computer and use it in GitHub Desktop.
class AjaxController < ApplicationController
def handle_checkbox
render :text => "You entered: #{params[:my_input]}"
end
end
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#my_checkbox').click(function() {
var checkbox = $(this);
checkbox.attr("disabled", true);
$.ajax($("form").attr("action"), {
type: "POST",
data: $("form").serialize(),
success: function(data) {
$('#output').append('<p>Received from server: ' + data + '</p>');
},
error: function() {
alert("Oops, something didn't work!");
},
complete: function() {
checkbox.attr("disabled", false);
}
});
});
});
</script>
</head>
<body>
<div id="page">
<form action="handle_checkbox">
<p><label for="my_input">Type something and click the checkbox</label> <input id="my_input" name="my_input" type="input"/></p>
<p><label for="my_checkbox">Checkbox</label> <input id="my_checkbox" name="my_checkbox" type="checkbox"/></p>
</form>
</div>
<div id="output"></div>
</body>
</html>
AjaxCheckbox::Application.routes.draw do
post "handle_checkbox" => 'ajax#handle_checkbox'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment