[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More


Simplifying jQuery Ajax calls in JavaScript

Published on
10,262 Points
Last Modified:
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:

    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

Open 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) {

    //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()
                    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
            type: "POST",
            url: this.pageName + "/" + this.methodName,
            data: dataStr,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
            error: function(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;

Open 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('d',new Date());

function successFunc(msg) {

function errorFunc(msg) {

Open 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.
Author:Luis Pérez
1 Comment
LVL 75

Expert Comment

by:Michel Plungjan
Why not use the built-in .get and .getJSON?

    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;

Open in new window


Featured Post

HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Join & Write a Comment

The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Next Article:

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month