Click here to Skip to main content
15,353,818 members
Articles / Web Development
Tip/Trick
Posted 1 Feb 2017

Tagged as

Stats

57.2K views
2 bookmarked

Ajax methods in TypeScript

Rate me:
Please Sign up or sign in to vote.
2.86/5 (5 votes)
1 Feb 2017CPOL1 min read
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

JavaScript
  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

JavaScript
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.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Prabu ram
Architect CGI
India India
No Biography provided

Comments and Discussions

 
SuggestionBetter to use promise Pin
Ankit Rana1-Feb-17 20:54
MemberAnkit Rana1-Feb-17 20:54 
GeneralRe: Better to use promise Pin
Prabu ram1-Feb-17 21:58
MemberPrabu ram1-Feb-17 21:58 
GeneralRe: Better to use promise Pin
Daniel Jursza5-Feb-17 0:47
MemberDaniel Jursza5-Feb-17 0:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.