1

Alright, so I'm a little confused on how to create callbacks in JavaScript and a mix of jQuery.

Here's what I'd like to do:

function saveArtDep(vars, callback) {
        $.ajax({
            url: 'j_artDepAjax.php',
            type: 'POST',
            data: vars,
            success: function(data) {
                // callback to fire when success
            }
        });  
}

The reason I want to do this is to be able to re-use this function and having a different "loading" message for what I need it for. In other words, the scenario would look like this:

$('div#job').html('loading...');

saveArtDep('job_id=3&update_art=true', function(){
             $('div#job').html('success!');
});

Any help would be great!

3 Answers 3

2

In saveArtDep the parameter callback refers to a function, so you can invoke it using callback()

function saveArtDep(vars, callback) {
        $.ajax({
            url: 'j_artDepAjax.php',
            type: 'POST',
            data: vars,
            success: function(data) {
                // callback to fire when success
                callback();
            }
        });  
}
Sign up to request clarification or add additional context in comments.

1 Comment

you've got a typo there - callbakc() should be callback()
1

You almost had it. You can pass anything to callback and we make sure that it is a function before executing it, in the below seen code.

function saveArtDep(vars, callback) {
    $.ajax({
        url: 'j_artDepAjax.php',
        type: 'POST',
        data: vars,
        success: function(data) {
            // callback to fire when success
            if (typeof callback === 'function') {
                callback();
            }
        }
    });  
}

2 Comments

You're absolutely right, I knew it was something as simple as that...I don't know why it didn't make sense to me at the time.
@Dimitri Thats okay :)
1
success: function(data) {
  if(typeof callback == 'function') {
      callback(data);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.