How to write jQuery function with callback?

I have the following function:

function loadProjects(pID) { $.ajax({ url: myURL, success: function (dataJS) {XXXXXXXXXXXXXXXX} }); } 

I call this function like this: loadProjects (1);

The problem is that I want to define the callBack function after success, and I would like to enable it when I load objects (1, callback: {regardless of what js is included here, returns after success})

How can I make a function accept a callback? How to pass the answer to this function?

thanks

+7
source share
6 answers
 function loadProjects(pID, callbackFunction) { $.ajax({ url: myURL, success: function (dataJS) { if(typeof callbackFunction == 'function') { callbackFunction.call(this, dataJS); } } }); } 

Using:

 loadProjects(pID, function(dataJS) { // do stuff with your dataJS, bear in mind you can call the parameter any name. }); 
+20
source

Here you can change your function so that it can receive a callback.

 function loadProjects(pID, callback) { $.ajax({ url: myURL, success: function (dataJS) { if ($.isFunction(callback)) { callback.call(); } } }); } 

You can use it here.

 function myCoolCallback() { alert("I am cool"); } loadProjects(123, myCoolCallback); 

Or you can use it with an anonymous function.

 loadProjects(123, function() { alert("I am cool"); }); 
+2
source
 function loadProjects(pID, callback) { $.ajax({ url: myURL, success: function (dataJS) { if (callback) { callback(); } } }); } 

Calling something like this:

 loadProjects(111, function() { alert('hello!'); }); 
+1
source

You can pass a function to another function as if it were any other object. Check this:

 function loadProjects(pId, callback) { $.ajax({ url: myUrl, success: function() { callback.call(); // <-- invokes your callback with no args } } 

You can also read the MDC documentation (function.call ()) .

+1
source
 function loadProjects(pID, callback) { $.ajax({ url: myURL, success: function (dataJS) { // your initial method declaration goes here ... // just call the callback method at the end of the success method callback(); } 
0
source

Try the following:

 var loadProjects = function(pID, callback) { var obj = { url: myURL }; if(typeof callback != "function"){ obj.success = function(dataJS){ loadProjects(1, /* Your callback func here */); }; } else { obj.success = callback; } $.ajax(obj); }; loadProjects(1, /* Your callback func here */); 
0
source

All Articles