How to pass a callback as a parameter to another function

I am new to ajax and callback functions, please forgive me if I realized that everything is wrong.

Problem: Can I send a callbackfunction as a parameter to another function that will execute the callback?

function firstFunction(){ //some code //a callback function is written for $.post() to execute secondFunction("var1","var2",callbackfunction); } function secondFunction(var1, var2, callbackfunction) { params={} if (event != null) params = event + '&' + $(form).serialize(); // $.post() will execute the callback function $.post(form.action,params, callbackfunction); } 
+73
javascript ajax callback call
Jun 24 2018-11-11T00:
source share
5 answers

Yeah. Function references are just like any other object reference; you can pass them to your heart.

Here is a more specific example:

 function foo() { console.log("Hello from foo!"); } function caller(f) { // Call the given function f(); } function indirectCaller(f) { // Call 'caller', who will in turn call 'f' caller(f); } // Do it indirectCaller(foo); // alerts "Hello from foo!" 

You can also pass arguments to foo :

 function foo(a, b) { console.log(a + " + " + b + " = " + (a + b)); } function caller(f, v1, v2) { // Call the given function f(v1, v2); } function indirectCaller(f, v1, v2) { // Call 'caller', who will in turn call 'f' caller(f, v1, v2); } // Do it indirectCaller(foo, 1, 2); // alerts "1 + 2 = 3" 
+115
Jun 24 2018-11-11T00: 00Z
source share

It could also be simple:

 if( typeof foo == "function" ) foo(); 
+12
Oct 27 '11 at 17:18
source share

If you google for a javascript callback function example , you will get a better understanding of javascript callback function example

Here's how to make a callback function:

 function f() { alert('f was called!'); } function callFunction(func) { func(); } callFunction(f); 
+10
Jun 24 '11 at 10:00
source share

Yes, of course, a function is an object and can be passed, but of course you must declare it:

 function firstFunction(){ //some code var callbackfunction = function(data){ //do something with the data returned from the ajax request } //a callback function is written for $.post() to execute secondFunction("var1","var2",callbackfunction); } 

Interestingly, your callback function also has access to every variable that you could declare inside firstFunction () (variables in javascript have a local scope).

+2
Jun 24. 2018-11-11T00:
source share

Example for CoffeeScript :

 test = (str, callback) -> data = "Input values" $.ajax type: "post" url: "http://www.mydomain.com/ajaxscript" data: data success: callback test (data, textStatus, xhr) -> alert data + "\t" + textStatus 
0
Dec 05 '13 at 14:37
source share



All Articles