Example: Simple jQuery MVC .NET API call

I decided to share some of my code snippets I use every day on a professional level.

Below is an example of calling/posting to an MVC action and handling the response.


//Main API calls
var api = {
    apiUrl: '/',
    callApi: function (callType, apiController, apiAction, data, callBack) {
        $.ajax({
            type: callType,
            url: this.apiUrl + apiController + "/" + apiAction,
            data: (callType === "POST") ? (data) ? JSON.stringify(data) : null : data,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        }).done(function (data) {
            callBack(data);
        });
    }
};

callType = "POST" / "GET" //as a string
apiController = //String name of your controller you're posting to. ie. "Home"
apiAction = //String name of you're action you're posting to. ie. "SubmitContactForm"
data = //A JSON object such as { "id":0, "name":"Kevin" }
callBack = //A function (as an object) to call when the call is complete.

Author: Kevin Dark - 10/5/2016 11:08:08 PM