How can I save MVC jQuery AJAX POSTs DRY?

I use Ajax for POST updates for the server:

$("#my-check-box").change(function () {

         var value = $(this).attr("checked");
         var url = '<%: Url.Routes().MyAction() %>';
         $.ajaxSetup({ cache: false });
         $.post(url, { **myActionParameterName**: value }, function (data) {

             if (data.result != "success") {
                 alert(data.error);
             }

         });


     });

I do not want to write the name of the parameter on the client side (in case of change), but is there any way to avoid this?

+5
source share
3 answers

The simple answer is no. At the end of the day, your AJAX should know how to invoke the parameter anyway.

What you are talking about is an abstraction, not a Do Not Repeat Yourself strategy. DRY means "Do not repeat your logic more than once", and not "Do not reference variables." If that were the case, you would not be able to refer to variables or parameters because you are technically repeating the name of the variable.

-, - , , . - , , , , .

/ , - .

, JSON JavaScript, DRY , , .

+3

jQuery.extend(), javascript api. MVC Conf

ajax stndard,

//A standard ajax api call that takes in a set of options
//This uses the jQuery extend method to merge the supplied options with a set of defaults
(function ($) {
    $.apiCall = function (options) {
        var config = $.extend({
            type: 'GET',
            data: {},
            contentType: 'application/x-www-form-urlencoded',
            success: function () { },
            error: function () { }
        }, options);

        $.ajax({
            type: config.type,
            url: config.url,
            contentType: config.contentType,
            data: config.data,
            success: function (result) {
                config.success(result);
            },
            error: function (result) {
                config.error(result);
                flashError('An error occured during the operation');
                //Okay, so this last bit is kindof a problem. Your nice, sharable api should not be referencing something
                //  on the master page. So you could pass it all the way down. But that means you have to have this defined
                //  lots of places. Or you could create another js object to wrap this. There are several ways to do this and
                //  how you do it is up to you.
            }
        });
    }
})(jQuery);

api

//User api object
//Uses the prototype method to make sure all objects of this type have required functions
var patientsApi = function () { }

userApi.prototype.getUsers = function (options,Id) {
    var config = $.extend({
        success: function () { },
        error: function () { }
    }, options);

    $.apiCall({
        url: '/Users/GetUser',
        data:{ID:Id},
        success: function (result) { config.success(result); }
    });
}

,

        var api = new userApi();
        var UserId= $("#UserId").val();

        api.getUsers({
            success: function (result) {          
            //Do some stuff
        }
     },userId);
+1

Here's what I do: I can't take all the merits, because I found examples from the example.

    var varType;
    var varUrl;
    var varData;
    var varContentType;
    var varDataType;
    var varProcessData;          
    //Generic function to call ASMX/WCF  Service        
    function CallService() 
    {
            $.ajax({
                type        : varType, //GET or POST or PUT or DELETE verb
                url         : varUrl, // Location of the service
                data        : varData, //Data sent to server
                contentType : varContentType, // content type sent to server
                dataType    : varDataType, //Expected data format from server
                processdata : varProcessData, //True or False
                success     : function(msg) {//On Successfull service call
                ServiceSucceeded(msg);                    
                },
                error: ServiceFailed// When Service call fails
            });
    }

Then we have a function of success

function ServiceSucceeded(result) {//When service call is successful
 ....
}

Then the function for failures

 function ServiceFailed(result) {
 ...
 }

Then, finally, an example of ajax function call:

 function GetWCFJSON() {
        varType = "POST";
        varUrl = "service/WCFService.svc/GetMyData";
        varData = '{"States": "' + $('#ddlStates').val() + '"}';
        varContentType = "application/json; charset=utf-8";
        varDataType = "json";
        varProcessData = true;
        CallService();
    }
0
source

All Articles