Simplifying jQuery Ajax calls in JavaScript

AID: 4613
  • Status: Published

1500 points

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know:

$.ajax({
    type: "POST",
    url: "MyPage.aspx/MyWebMethod",
    data: "{parameter:value,parameter:value}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        //function called successfull
    },
    error: function(msg) {
        //some error happened
    }
});
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window


I don't know if for you it's the same, but for me is soooo tedious to write the calls with this syntax. Moreover, previously it's necessary to build the string with the parameters to pass to the WebMethod, following the known rules: strings must be passed in quotes, numbers do not, etc.

So I decided to create a small but useful JavaScript class to help me with this particular issue, and now that I've done the jQuery Ajax calls are much friendly to me.

In the class constructor I pass the page name, the method name, and the success and error functions. Later, I do as many calls to the addParam method as I need. And finally I call the run method to do the Ajax call. The success and error functions must be written separately.

The parameters are treated according to their type. If the parameter is a string, I use quotes; if it's a number, I do not. A special case are date parameters. In this case, I use the getTime() function of the JavaScript date object, which gives me the number of milliseconds in the date since January 1, 1970. Later, I translate that value to UTC time so I get a final milliseconds number that I can pass to my VB.net (or C#) code as an Int64 value that I can use to rebuild the date value in .Net.

This is the complete listing of my jAjax class (with the date helper function at the end):

function jAjax(pageName, methodName, successFunc, errorFunc) {
    //stores the page name
    this.pageName = pageName;
    //stores the method name
    this.methodName = methodName;
    //stores the success function
    this.successFunc = successFunc;
    //stores the error function
    this.errorFunc = errorFunc;
    //initializes the parameter names array
    this.paramNames = new Array();
    //initializes the parameter values array
    this.paramValues = new Array();

    //method for add a new parameter (simply pushes to the names and values arrays)
    this.addParam = function(name, value) {
        this.paramNames.push(name);
        this.paramValues.push(value);
    }

    //method to run the jQuery ajax request
    this.run = function() {
    //initializes the parameter data string
        var dataStr = '{';
        //iterate thru the parameters arrays to compose the parameter data string
        for (var k = 0; k < this.paramNames.length; k++) {
            //append the parameter name
            dataStr += this.paramNames[k] + ':';
            if (typeof this.paramValues[k] == 'string') {
                //string parameter, append between quotes
                dataStr += '"' + this.paramValues[k] + '",';
            } else if (typeof this.paramValues[k] == 'number') {
                //number parameter, append "as-is" calling toString()
                dataStr += this.paramValues[k].toString() + ',';
            } else if (typeof this.paramValues[k] == 'object') {
                if (this.paramValues[k].getTime != undefined) {
                    //date value
                    //call to my getUtcTime function to get the number of
                    //milliseconds (since january 1, 1970) in UTC format
                    //and append as a number
                    dataStr += getUtcTime(this.paramValues[k]).toString() + ',';
                } else {
                    //object value
                    //because I don't know what's this, append the toString()
                    //output
                    dataStr += '"' + this.paramValues[k].toString() + '",';
                }
            }
        }
        //if some parameter added, remove the trailing ","
        if (dataStr.length > 1) dataStr = dataStr.substr(0, dataStr.length - 1);
        //close the parameter data string
        dataStr += '}';

        //do the jQuery ajax call, using the parameter data string
        //and the success and error functions
        $.ajax({
            type: "POST",
            url: this.pageName + "/" + this.methodName,
            data: dataStr,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                successFunc(msg);
            },
            error: function(msg) {
                errorFunc(msg);
            }
        });
    }
}

function getUtcTime(dateValue) {
    //get the number of milliseconds since january 1, 1970
    var time = dateValue.getTime();
    //get the UTC time offset in minutes. if you created your date with
    //new Date(), maybe this contains a value. but if you compose the date
    //by yourself (i.e. var myDate = new Date(1984,5,21,12,53,11)) this will
    //be zero
    var minutes = dateValue.getTimezoneOffset() * -1;
    //get the milliseconds value
    var ms = minutes * 60000;
    //add to the original milliseconds value so we get the GMT exact value
    return time + ms;
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:

Select allOpen in new window



And this is the syntax in use:

var ajaxCall = new jAjax('MyPage.aspx','MyWebMethod',successFunc,errorFunc);
ajaxCall.addParam('s','this is a string');
ajaxCall.addParam('n',34);
ajaxCall.addParam('d',new Date());
ajaxCall.run();

function successFunc(msg) {
    ...
}

function errorFunc(msg) {
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window



As an additional benefit, you can re-use the success and error functions for several ajax calls.

Hope that helps to you!! Feel free to use the jAjax class in your applications.
Asked On
2011-03-02 at 01:01:04ID4613
Tags

JavaScript

,

jQuery

,

Ajax

,

ASP.net

Topic

JavaScript

Views
940

Comments

Expert Comment

by: mplungjan on 2011-03-08 at 05:28:59ID: 24403

Why not use the built-in .get and .getJSON?

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });
                                        
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top JavaScript Experts

  1. leakim971

    511,289

    Sage

    2,168 points yesterday

    Profile
    Rank: Genius
  2. mplungjan

    291,279

    Guru

    2,800 points yesterday

    Profile
    Rank: Savant
  3. nap0leon

    195,491

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  4. Proculopsis

    182,948

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  5. COBOLdinosaur

    157,309

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  6. chaituu

    130,684

    Master

    0 points yesterday

    Profile
    Rank: Sage
  7. Ray_Paseur

    130,217

    Master

    330 points yesterday

    Profile
    Rank: Savant
  8. tommyBoy

    125,345

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. StingRaY

    114,318

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  10. DaveBaldwin

    80,081

    Master

    336 points yesterday

    Profile
    Rank: Genius
  11. ansudhindra

    79,054

    Master

    2,000 points yesterday

    Profile
    Rank: Wizard
  12. ChrisStanyon

    62,768

    Master

    800 points yesterday

    Profile
    Rank: Sage
  13. hielo

    61,266

    Master

    0 points yesterday

    Profile
    Rank: Savant
  14. HainKurt

    59,030

    Master

    0 points yesterday

    Profile
    Rank: Genius
  15. BuggyCoder

    54,739

    Master

    0 points yesterday

    Profile
    Rank: Sage
  16. mroonal

    54,339

    Master

    10 points yesterday

    Profile
    Rank: Sage
  17. tagit

    54,093

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  18. gurvinder372

    52,824

    Master

    10 points yesterday

    Profile
    Rank: Genius
  19. basicinstinct

    52,586

    Master

    0 points yesterday

    Profile
    Rank: Genius
  20. JonNorman

    45,158

    2,200 points yesterday

    Profile
    Rank: Master
  21. Lalit-Chandra

    44,420

    0 points yesterday

    Profile
    Rank: Master
  22. xmediaman

    36,450

    3,800 points yesterday

    Profile
    Rank: Guru
  23. kozaiwaniec

    33,100

    0 points yesterday

    Profile
    Rank: Guru
  24. Kravimir

    32,700

    0 points yesterday

    Profile
    Rank: Genius
  25. designatedinitializer

    32,300

    0 points yesterday

    Profile
    Rank: Master

Hall Of Fame