I want to use jQuery ajax to retrieve data from a server.
I want to put the success callback function definition outside the
.ajax()
dataFromServer
.ajax()
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:
function getData() {
$.ajax({
url : 'example.com',
type: 'GET',
success : handleData
})
}
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 way handleData
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:
var myfunction = function(){}
Those are only available when the interpreter passed them.
See this question for more information about the 2 ways of declaring functions