JQuery callback for a previously defined function

I'm still learning jQuery (and, as a result, a bit of JavaScript), but I can't figure out how to use the previously defined function in the callback.

Say I have:

<script> $(document).ready(function() { function ajax_start() { alert("starting..."); } }); </script> 

And I want to use this in another function, for example:

 <script> $(document).ready(function() { $.ajax({ beforeSend: ajax_start(), url: "insert_part.php", type:"POST", data: "customer="+customer }); }); </script> 

Will it be right? (I suppose it's not like this is not ...), what is the correct way to call back?

+4
source share
3 answers

To close.

 $(document).ready(function() { function ajax_start() { alert("starting..."); } $.ajax({ beforeSend: ajax_start, // <== remove the parens url: "insert_part.php", type:"POST", data: "customer="+customer // <== as Skilldrick pointed out, // remove the trailing comma as well }); }); 

You need to do this because

  • ajax_start() evaluates the value returned by a function called ajax_start , but
  • ajax_start evaluates the function itself .

Edit Repeat: OP Comment

"how to include the second function in the callback. Something like: beforesend: ajax_start, other_function (isn’t it?)?

There are several ways to do this. Combine them using an anonymous function:

 $.ajax({ // if you need the arguments passed to the callback beforeSend: function (xhr, settings) { ajax_start(); other_function(); }, url: "insert_part.php", type:"POST", data: "customer="+customer }); 

Or simply declare a named function that does what you want, and then use it:

 function combined_function(xhr, settings) { ajax_start(); other_function(); } $.ajax({ beforeSend: combined_function, url: "insert_part.php", type:"POST", data: "customer="+customer }); 
+7
source

Change the value of beforeSend to ajax_start . In other words, remove the parentheses.

In parentheses, you call ajax_start() and set beforeSend to the return value of ajax_start() (in this case, I think it will be undefined ).

+2
source

just remove the parentheses, then you are referencing the "function" object. The function () calls the function, so you must pass the return value ajax_start.

 $.ajax({ beforeSend: ajax_start, url: "insert_part.php", type:"POST", data: "customer="+customer, }); }); 
+2
source

Source: https://habr.com/ru/post/1335553/


All Articles