views:

101

answers:

3

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();
            }
        });
    });

}
+1  A: 

Since all of this code involves submitting groups of INPUT elements using AJAX, you could try putting them in FORM elements (if you haven't already) and using the jQuery Form Plugin to upgrade them to AJAX. This also gives you fallback behavior if Javascript is disabled for whatever reason.

Tobias Cohen
Thanks but most of the functions are not actually posting form elements, it's more like getting url parameters to pass id's.
dean nolan
+1  A: 

You could break up the .ajax callbacks into smaller functions by using the higher level jQuery.post( url, [data], [callback], [type] ).

Jason Rowe
I think this is the first step I need to take as a lot of the callbacks are the same as well as some data parameters.
dean nolan
+2  A: 

Minor nit: Constructing URL arguments should generally be done by a method rather than with concatenation because then you can ensure that you are URL-escaping the values correctly. Example: if 'restaurantId' contained an ampersand (&) character, then your data= variable would be corrupted. So, I suggest refactoring this into a dict ({restaurantId: restaurantId, ...}) or passing it to a method (something like: buildQueryArguments(name1, value1, name2, value2, ...)). Depending on your implementation, that method could be implemented to extract the values from the form fields directly.

However, your best bet is probably to use something like the jQuery Form Plugin (http://jquery.malsup.com/form/) because this will give your users a better user experience in case they don't have full JS support.

Otherwise, there are some cheap refactorings you can do (encapsulate the .ajax() call with something that fill sin default args, for example), but it isn't going to make much of a difference for you in the long run.

lucas-insasho