Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery callback to previously defined function

I'm still learning JQuery (and as a result a little JavaScript) but I can't seem to find out how to use a previously defined function in a callback.

Say I have:

<script>
$(document).ready(function() {

function ajax_start() {
                      alert("starting...");
                      }

});
</script>

And I wish to use this in another function e.g:

<script>
$(document).ready(function() {

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

Would this be correct? (I assume not as it doesn't...) what is the proper way of doing a callback?

like image 225
Alex Avatar asked Dec 22 '22 19:12

Alex


1 Answers

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 to the value returned by executing the function named ajax_start, but
  • ajax_start evaluates to the function itself.

Edit re: OP comment

"how would I include a second function in the callback. Something like- beforesend: ajax_start,other_function (obv. not exactly like that)?"

There are a couple ways to do it. 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 just 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
});
like image 51
Matt Ball Avatar answered Jan 01 '23 21:01

Matt Ball