views:

44

answers:

2

Give the following Ajax call in jQuery:

  {
  .
  .
  .
  ,
  getSomeData: function(args, myUrl, foo) {
        $.ajax( {
        type: "GET",
        url:  myUrl,
        data: args,
        async: true,
        dataType: 'json',
        success: myHandler  

         });
 },

   myHandler: function (data, textStatus, oHTTP, foo){   ...   }  

};

can value foo be somehow appended to the arguments that are passed to success-handler myHandler? Is there any way to pass a value up to the server on the GET, and have that value come back to the client in a round-trip, reappearing in the success-handler's arguments list? I cannot change the structure of what is returned in data.

Thanks

A: 

If you declare myHandler within the request, you can use a closure.

getSomeData: function(args, myUrl, foo) {
        $.ajax( {
        type: "GET",
        url:  myUrl,
        data: args,
        async: true,
        dataType: 'json',
        success: function (data, textStatus, oHTTP){   ...   }  

         });
 },

this way, foo will be available to you inside the success callback.

Unicron
A: 

If you're $.ajax call is in a class and the success callback is passed a method of that class, it does not work.

EDIT: Here is the answer. Note that I am defining the function ajaxCall as a method in a class. I define this.before, this.error, and this.success as methods of ajaxCall because they can call methods from the superClass.

function main(url){
  this.url = url;

  this.ajaxCall = function(){

          this.before = function(){
                  //Can call main class methods
                  };
          this.error = function(){
                         //Can call main class methods
                       };
          this.success = function(data){
                           //Can call main class methods
                         };

          //This is how you pass class arguments into the success callback
          var that = this;

          $.ajax({ 
            url: this.url,
            type: 'GET',
            dataType: 'json',
            beforeSend: this.before(),
                error: this.error(),
            success: function(data){that.succes(data);}
          });

  //Run internally by calling this.ajaxCall() after it is defined
  //this.ajaxCall();
}

//Or externally
var main = new main(SOME_URL);
main.ajaxCall();
Chris