I want to use jQuery ajax to retrieve data from a server.
I want to put the success callback function definition outside the .ajax()
block like the following. So do I need to declare the variable dataFromServer
like the following so that I will be able to use the returned data from the success callback?
I've seen most people define the success callback inside the .ajax()
block. So is the following code correct if I want to define the success callback outside?
var dataFromServer; //declare the variable first
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData(dataFromServer)
})
}
function handleData(data) {
alert(data);
//do some stuff
}
Just use:
The
success
property requires only a reference to a function, and passes the data as parameter to this function.You can access your
handleData
function like this because of the wayhandleData
is declared. JavaScript will parse your code for function declarations before running it, so you'll be able to use the function in code that's before the actual declaration. This is known as hoisting.This doesn't count for functions declared like this, though:
Those are only available when the interpreter passed them.
See this question for more information about the 2 ways of declaring functions
In your component i.e angular JS code:
after few hours play with it and nearly become dull. miracle came to me, it work.
The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a
success
callback. You should return the result of$.ajax
and then use the.done
,.fail
etc methods to add the callbacks outside of the$.ajax
call.This decouples the callback handling from the AJAX handling, allows you to add multiple callbacks, failure callbacks, etc, all without ever needing to modify the original
getData()
function. Separating the AJAX functionality from the set of actions to be completed afterwards is a good thing!.Deferreds also allow for much easier synchronisation of multiple asynchronous events, which you can't easily do just with
success:
For example, I could add multiple callbacks, an error handler, and wait for a timer to elapse before continuing:
Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.
I would write :
I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the
sucess:
i.e.the handleData function will be called and the parameter passed to it by the ajax function.