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
}
Try rewriting your success handler to:
The success property of the ajax method only requires a reference to a function.
In your handleData function you can take up to 3 parameters:
You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters:
Function( Object data, String textStatus, jqXHR jqXHR )