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!

asked Dec 17, 2013 at 4:07

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();
 }
 }); 
}
Sridhar R
20.4k7 gold badges41 silver badges35 bronze badges
answered Dec 17, 2013 at 4:08
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();
 }
 }
 }); 
}
answered Dec 17, 2013 at 4:10

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);
 }
}
answered Dec 17, 2013 at 4:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.