Maya
Maya

Reputation: 1412

Retain the context of JQuery ajax function

I have an old code which is dependant on JQuery 1.3.2 that uses the following ajax call

function ChangeContent(url, somepageobject) {
   var xhrobj = $.ajax({
       url: url,
       context: somepageobject,
       callback: doFurtherStuff,
       success: function(data) {
                somepageobject.html($(data));
                this.callback.call(this.context[0], data, "ok"); // >> Code breaks here
           }
  });
  return xhrobj;
 }

Problem with the code above is that this.callback is null when I upgraded to JQuery 1.8.1, most importantly the ChangeContent function is being used in different places and is outside my control (its used as as an API for external users...etc). An example of the usage of the above is like this:

xhr_object = ChangeContent("/someurl, $("#resultContainer"));

function doFurtherStuff(responseText, statusText, XMLHttpRequest) 
{
   var identifier = '#' + this.id;
   ...
}

Notice that the doFurtherStuff must have the correct "this" object value which is the context specified in ChangeContent function. When I tried to use different deferred then() ...etc. functions in JQuery 1.8.1 to solve the above this.callback.call(this.context[0], data); problem after the upgrade the "this" object in the callback function had different value since I guess the new JQuery library handles that differently.

Is there anyway to fix the error above while limiting the change to ChangeContent function only as I try to avoid asking all users to change the way they call and handle call backs from that function?

Upvotes: 0

Views: 339

Answers (1)

Kevin B
Kevin B

Reputation: 95048

When you add the context option, you are telling jQuery what this should be inside of the success callbacks. That means you can't access the options passed into the ajax request. Either don't supply a context, or pass in the callback manually.

function ChangeContent(url, somepageobject) {
   var callback = doFurtherStuff;
   var xhrobj = $.ajax({
       url: url,
       context: somepageobject,
       success: function(data) {
                somepageobject.html($(data));
                callback.call(this[0], data, "ok"); // >> Code breaks here
           }
  });
  return xhrobj;
}

Update: If you want to instead continue using your code as-is, simply rename the context property.

function ChangeContent(url, somepageobject) {
   var xhrobj = $.ajax({
       url: url,
       thecontext: somepageobject,
       callback: doFurtherStuff,
       success: function(data) {
                somepageobject.html($(data));
                this.callback.call(this.thecontext[0], data, "ok"); // >> Code breaks here
           }
  });
  return xhrobj;
}

Upvotes: 1

Related Questions