Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hussaintamboli/11391333 to your computer and use it in GitHub Desktop.
Save hussaintamboli/11391333 to your computer and use it in GitHub Desktop.
The right way of Ajax for Edit, Save and Cancel scenarios for Web
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<span id="spanId" style="float:left;"> Guest </span>&nbsp;
<input type="text" id="inputField" style="display:none;">
<input type="submit" value="Edit" name="editButton" id="editButton" onclick="editIt();" />
<input type="submit" value="Save" id="saveButton" style="display:none;" onclick="saveIt(this);">
<input type="submit" value="Cancel" id="cancelButton" style="display:none;" onclick="$('#saveButton').hide();$('#editButton').show(); $(this).hide();$('#inputField').hide(); $('#spanId').show();">
</body>
<script type="text/javascript">
window.editIt = function() {
$('#saveButton').show();
$('#cancelButton').show();
$('#inputField').show();
$('#editButton').hide();
}
window.saveIt = function (elm) {
var params = {
'key': 'value'
};
$.post("controller/action", params, function (data) {
// client provided a valid input
if (input in validInputs) {
// set output corresponding to the valid input
$('#spanId').html(output);
} else {
$("#spanId").html("Invalid ");
}
}).fail(function (err, status) {
// error 4xx : client side errors (e.g. controller/action does not exist)
// error 5xx : server side errors (like db failure)
$("#spanId").html("Error ");
}).always(function () {
$('#saveButton').hide();
$('#cancelButton').hide();
$(elm).hide();
$('#editButton').show();
$('#inputField').hide();
$('#spanId').show();
});
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment