1

if I have a function defined earlier, do I need to include parenthesis when specifying that it should be used for a success callback?

what would be the difference if I did?

as in

function fish_food(){//do something}

$.ajax({
    url: '/',
    success: fish_food
});

or

$.ajax({
    url: '/',
    success: fish_food()
});
mjr
  • 1,947
  • 5
  • 24
  • 37

7 Answers7

5

fish_food on its own (without parens) acts as a reference to the function object. It allows you to pass the reference to the function around to be invoked at some later date.

fish_food() (with parens) is a function invocation expression, which causes the function to be executed. The function code is evaluated and run with a value optionally being returned.

With the AJAX code you supplied (and all async JavaScript involving callbacks) you want to use the fish_food version (without parens). This passes the AJAX code a reference to your success function, to be executed asynchronously once the AJAX code has completed its round trip to the server and back.

Jed Richards
  • 11,346
  • 2
  • 21
  • 33
4

No.

Parentheses will tell the browser that function fish_food needs to be executed immediately, and the value has to be returned to a success property.

VisioN
  • 132,029
  • 27
  • 254
  • 262
0

You want the no-parens version. The reason is that the parentheses tell JavaScript to execute the function right away, rather than just reference it by name, so your success callback would actually be the results of invoking fish_food() whenever you are executing the AJAX call (which is probably going to be an error involving undefined).

Hank Gay
  • 65,372
  • 31
  • 148
  • 218
0

this will work

$.ajax({
    url: '/',
    success: fish_food
});
Shreedhar
  • 5,084
  • 3
  • 19
  • 27
0

You don't need the parenthesis. Using parens would invoke the function, what it needs is just a name which is equivalent to function pointers in C/C++.

g13n
  • 3,030
  • 2
  • 22
  • 19
0

Having the parenthesis causes the function to execute then and there, that is why you need first version else success stores return value of the function.

Ankur
  • 11,601
  • 5
  • 32
  • 66
0
$.ajax({
    url: '/',
    success: fish_food
});

is correct.

When you use success: fish_food(), it will be executed right away and the return is set to success.

Selvakumar Arumugam
  • 76,636
  • 14
  • 118
  • 132