Tuesday, 14 August 2012

JQuery Ajax Maintaining State Between Multiple Requests:-

JQuery ajax function is used to call the server resources. While making the ajax request  probability of getting errors is more. In my scenario i am calling wcf REST service to get live cricket scores for multiple matches by sending matchId .If the call is success some how we can know the matchId ,but if error occurs there is no way to find the matchId of that request.To solve this issue we have to maintain state between multiple requests.
Using jquery ajax context property and object oriented concepts  we can  maintain state between multiple ajax requests.
In the below example i am having the wcf REST service which gives the live cricket scores,and javascript client which makes the ajax request.

    //Call the wcf service.
        function CallService(matchId) {

            this.matchId = matchId;

            //Make the ajax request.
            this.getScore = function () {

                //Ajax request.
                    //Context object to maintain state.
                    context: this,

                    //Url of wcf service.
                    url: 'http://localhost:6247/Service.svc/GetScore?matchId=' + this.matchId.toString(),

                    //Method type.
                    type: 'GET',

                    //Asynchornous call.
                    async: true,

                    //Success event.
                    success: function (res) {

                        //Disply score.

                    //Error event.
                    error: function (err) {

                        //Get score again.

        //Create call service object.
        var obj = new CallService("M1");

        //Call getscore function.

Here I didn’t give the code for wcf REST service which is out of scope,but it contains the simple GetScore function which takes the matchId as input and returns the live cricket score of that matchId.
Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…

No comments:

Post a Comment