<

Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

Simplifying jQuery Ajax calls in JavaScript

Published on
9,874 Points
3,874 Views
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:

$.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
    }
});

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) {
        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;
}

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('n',34);
ajaxCall.addParam('d',new Date());
ajaxCall.run();

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.
0
Comment
Author:Luis Pérez
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 75

Expert Comment

by:Michel Plungjan
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;
    });
  });

Open in new window

0

Featured Post

Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

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…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month