I have created a jQuery plugin that is used to create html on a page with the xml that it reads from a webservice call. As a backup, if the webservice call fails, there is default xml stored in a var to use to build the html. Right now, the webservice is not available to me so I am stuck testing the failure scenario with dummy xml. I have everything written and working with the $.ajax call excluded, when I included the $.ajax call to the webservice in my code it still works fine, but chaining is broken.
I know to "return this;", and I have implemented the $.when().then() wrapping my $.ajax call to take care of any problems that the asynchronous nature of an ajax call may introduce, but chaining still does not work. The firebug console always tells me that my method return is undefined when it gets to the next method in the chain, which leads me to believe I am not in fact returning "this" at all even though it looks to me like I am. My code is below (replaced a lot with pseudocode to save time):
(function( $ ) {
$.fn.createHtmlFromWS = function( options ) {
var $this = $(this);
//function to output the parsed xml as HTML appended to the jQuery object the plugin was called on
function buildNav(dispXml){
//logic to append xml to $this as custom html goes here
return $this;
}
//fallback xml if webservice call fails
var failXml = '<?xml version="1.0" encoding="utf-8"?><hello><world>earth</world></hello>';
//dummy service url to force webservice fail scenario
var serviceUrl = 'http://1234lkjasdf/test';
//Note: this call that does not attempt $.ajax call to webservice WORKS with chaining
//return buildNav($.parseXML(failXml));
//call to webservice
$.when($.ajax({
type: 'GET',
dataType: 'xml',
url: serviceUrl,
timeout: 10,
})).then(function(a1) { //function to call if succeeded
return buildNav($.parseXML(a1[2].responseXml));
}, function(){ //function to call if failed
console.log("in the error part of then"); //Note: this is output to log, I know i'm in the right spot
//This line does not seem to be returning $then which is required for chaining, although it is building the html as expected
return buildNav($.parseXML(failXml));
});
};
}) ( jQuery );
This is due to the fact that you are returning from your callback functions, not the function itself. By the time your AJAX request has completed, your original function has long since returned undefined
.
Just after your AJAX call, and just before the end of the function, you'll probably want to return $this;