65.9K
CodeProject is changing. Read more.
Home

Ajax methods in TypeScript

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.86/5 (5 votes)

Feb 2, 2017

CPOL

1 min read

viewsIcon

67335

I am just trying to wrap the jquery ajax methods under Typescript to give a better control from the rest of the code.

Introduction

TypeScript is a superset of JavaScript with lot of benefits over plain JavaScript code. Mostly it is object oriented and compile time safety i.e. your code will not build if there is something wrong in the script which is  not possible in plain JavaScript. Those not familiar with TypeScript please spend some time here before reading further.

 

Background

The idea began when we noticed the developers writing code to call ajax methods in each page they develop that leads to lot of duplicates and maintenance nightmare. So we decided to extract all ajax calls into a single TypeScript file and let the developers call only the methods exposed by it. It has a lot of benefits

  • better control
  • global error handling. if the calling code does not handle error then the global error handler handles it
  • easy maintenance
  • flexible 

Using the code

Let's look at the complete Ajax code here

  module Ajax {
    export class Options {
        url: string;
        method: string;
        data: Object;
        constructor(url: string, method?: string, data?: Object) {
            this.url = url;
            this.method = method || "get";
            this.data = data || {};
        }
    }

    export class Service {
        public request = (options: Options, successCallback: Function, errorCallback?: Function): void => {
            var that = this;
            $.ajax({
                url: options.url,
                type: options.method,
                data: options.data,
                cache: false,
                success: function (d) {
                    successCallback(d);
                },
                error: function (d) {
                    if (errorCallback) {
                        errorCallback(d);
                        return;
                    }
                    var errorTitle = "Error in (" + options.url + ")";
                    var fullError = JSON.stringify(d);
                    console.log(errorTitle);
                    console.log(fullError);
                    that.showJqueryDialog(fullError, errorTitle);
                }
            });
        }
        public get = (url: string, successCallback: Function, errorCallback?: Function): void => {
            this.request(new Options(url), successCallback, errorCallback);
        }
        public getWithDataInput = (url: string, data: Object, successCallback: Function, errorCallback?: Function): void => {
            this.request(new Options(url, "get", data), successCallback, errorCallback);
        }
        public post = (url: string, successCallback: Function, errorCallback?: Function): void => {
            this.request(new Options(url, "post"), successCallback, errorCallback);
        }
        public postWithData = (url: string, data: Object, successCallback: Function, errorCallback?: Function): void => {
            this.request(new Options(url, "post", data), successCallback, errorCallback);
        }

        public showJqueryDialog = (message: string, title?: string, height?: number): void => {
            alert(title + "\n" + message);
            title = title || "Info";
            height = height || 120;
            message = message.replace("\r", "").replace("\n", "<br/>");
            $("<div title='" + title + "'><p>" + message + "</p></div>").dialog({
                minHeight: height,
                minWidth: 400,
                maxHeight: 500,
                modal: true,
                buttons: {
                    Ok: function () { $(this).dialog('close'); }
                }
            });
        }
    }
}

 

And the sample client

module MySite {
    export class CustomerPage {
        constructor() {
            this.loadCustomers();
        }
        loadCustomers = (): void => {
            var service = new Ajax.Service();
            var customerUrl = "http://mysiteapi/customer";
            //Sample 1 - request method no error handling. in this case global error handler handles it
            var options = new Ajax.Options(customerUrl);
            service.request(options, function (d) {
                $("#grid").html(d);
            });
            //Sample 2 - request method but handling error
            var options = new Ajax.Options(customerUrl);
            service.request(options, function (d) {
                $("#grid").html(d);
            }, function (d) {
                alert("Error - " + d);
            });
            //Sample 3 - use get
            service.get(customerUrl, function (d) {
                $("#grid").html(d);
            });
            //Sample 4 - get with data
            service.getWithDataInput(customerUrl, { ProductId: 1 }, function (d) {
                $("#grid").html(d);
            });
        }
    }
}

I guess you understand most of them how it works by looking at the code, however let me brief how this is done

You have two modules

  • Ajax - it has two classes Options and Service. Service class offers method for making ajax calls. request is all-in-one where you can use it for any kind of calls whereas the other methods are for specific purpose. get can be used only for get request while post method used only for post request
  • MySite - this is where you put page specific or module specifc scripts which uses Ajax module for making ajax calls. In the example above I have provided four different ways you make ajax calls to get customer records and that gave you an idea of how to use other methods.