Skip to content Skip to sidebar Skip to footer

How Do I Callback With Js Function

I'm having trouble with callbacks mainly because I don't understand how they're working (or supposed to work). I have my function: function checkDuplicateIndex(values, callback)

Solution 1:

This ended up being a long answer, so I'm going to try to split it into pieces.

Functions in Javascript

So within javascript, a function is an object that can be passed around, assigned to a variable, etc, just like any other data type. The difference is that a function, rather than being a string of text, number, etc, is a block of code waiting to be executed.

This is often confusing to people starting out with programming because usually when you write code, it is executed when you run the program. But for functions, this is not the case. When you write code inside a function, it waits there not executing until you call the function. If you do not call the function, the code is never executed. Let's check out a quick example:

functionsay_hello(){
  console.log('hello!');
}

What you see here is called a function declaration. This means you are creating a function, which is a block of code waiting to be executed. If you run this code, nothing will be logged to the console. Now let's look at a function call.

function say_hello(){
  console.log('hello!');
}

say_hello();

So here we declare the function just like before, but below we call it. A function call is just the name of the function followed by open and close parens. If the function takes arguments, they will be inside the parens, but no need to worry about that for now. If you were to run this code, you would in fact see hello! logged to the console, because the function was called, which executes the code inside.

Asynchronous Code

Now, let's switch gears for a second. When you make a jquery ajax call, jquery abstracts a lot of code into the library. They take care of setting up the XMLHttpRequest, firing it off to the place you specify, and collecting the result, and they do this in a way that works cross-browser. But since javascript is asynchronous, as soon as the ajax call goes off, javascript keeps executing code after the ajax call, because who wants to wait around for someone else's server to respond while you could be still getting in that work. So if you fire off something like this:

$.ajax({
  url: 'http://google.com',
  success: function(){ console.log('done!') }
});

console.log('after ajax call');

...you may be surprised to find that it logs after ajax callbefore logging done!. This is because, as stated earlier, in javascript calls that deal with I/O are often asynchronous.

So if the ajax call is made and it immediately continues executing code even if the ajax call has not finished, how can we specify code that will run when it's finished? This is where everything comes together. By providing jquery with a function, which as we remember is a block of unexecuted code, we can provide a way for ourselves to write code that is executed only after the ajax call has finished by passing the block of unexecuted code to jquery and saying essetially "hey jquery, take this code, and when the ajax call is finished, call it and pass in any data you got out of it." How convenient!

The way we do this is through the success and error properites of jquery's ajax function. If the request was successful, it will call the function we pass to success, and I assume you can guess what happens if there was an error.

Putting It All Together

Asynchronous code and first class functions are two of the most confusing parts about javascript, and once you understand these two concepts, you'll be in a great spot, although it may take a while to get there. So it's important to think carefully about it and experiment. Let's talk through a couple ways to handle the example you are working with here, about jquery ajax.

First, we can try making our own function and passing the name of the function to the success handler. Then when it comes back, it will call the function. Let's take a look:

var my_callback = function(data){
  console.log(data);
}

$.ajax({
  url: 'http://google.com',
  success: my_callback
});

This is an interesting way of doing it. Here we have assigned an anonymous function to a variable, then passed the variable name to the success handler. This will work fine. Now let's try another way:

functionmy_callback(data){
  console.log(data);
}

$.ajax({
  url: 'http://google.com',
  success: my_callback
});

Here, we define a named function and do the same thing. This will work the same way. Named functions in javascript can actually be declared after the are used, so you could move the function declaration below the ajax call and it would still work. Try this out. This is a nice advantage to named functions.

Finally, let's take a look at a third way we could handle it:

$.ajax({
  url: 'http://google.com',
  success: function(data){
    console.log(data);
  }
});

Here, we define an anonymous function right inline on the success handler. This works exactly the same as either of the other two options. In all three of these ways, jquery receives a function declaration, and calls it when it needs to, which is after the ajax request has come back.

I know this is a super long answer, but what you are confused about here are some of the core concepts of javascript, and I thought it would be more helpful to go over them here than to just solve your problem and give you the answer without explanation of the concepts. In fact, I haven't actually tackled your problem here at all, but you will easily be able to solve it yourself after understanding these concepts. If you are still having trouble, drop a comment and I'll try to clarify more.

Solution 2:

Given the above code, you would call it like this within your submit handler:

var values = '…';
checkDuplicateIndex(values, function(returnValue) {
    alert(returnValue);
    // additional processing here...
});

Post a Comment for "How Do I Callback With Js Function"