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?
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, butajax_start evaluates to the function itself."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
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With