I have a lot of code in the admin area of my site that is, basically just CRUD operations using AJAX posting.
I was wondering if you had any tips on refactoring these type of functions either into generic functions or classes etc.
Here is some sample code, though a lot of this is duplicated in other functions with just different ajax parameters:
function BindAddMenuHeaderOption() {
$("#AddMenuHeaderOption").click(function (e) {
e.preventDefault();
var headerOptionId = jQuery.trim($("#HeaderOptions").val());
var menuHeaderId = jQuery.trim($("#MenuHeaderId").val());
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuHeaderOption",
data: "menuHeaderId=" + menuHeaderId + "&headerOptionId=" + headerOptionId,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#ModalContent").empty();
$("#ModalContent").append(domElement);
BindAllBehaviours();
}
});
});
}
function BindAddMenuItem() {
$(".AddMenuItem").click(function (e) {
e.preventDefault();
//get header id from link by removing addmenuitem from this.id
var currentId = $(this).attr("id").replace("AddMenuItem", "");
//get itemnumber, itemname, itemdetails from textboxes with same header id
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
var itemName = jQuery.trim($("#ItemName" + currentId).val());
var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuItem",
data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
var newNum = parseInt(itemNumber) + 1;
$("#ItemNumber" + currentId).val(newNum);
BindAllBehaviours();
}
});
});
}
function BindUpdateMenuItem() {
$(".UpdateMenuItem").click(function (e) {
e.preventDefault();
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#UpdateItemNumber").val());
var itemName = jQuery.trim($("#UpdateItemName").val());
var itemDetails = jQuery.trim($("#UpdateItemDetails").val());
var vars = GetHtmlParameters($(this));
$.ajax(
{
type: "POST",
url: "/Menu/UpdateMenuItem",
data: "reastaurantId=" + restaurantId + "&menuItemId=" + vars["menuItemId"] + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
BindAllBehaviours();
}
});
});
}