jQuery ajax success callback function definition
Asked Answered
U

8

98

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
}
Utu answered 7/2, 2013 at 15:19 Comment(0)
L
96

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

Levitate answered 7/2, 2013 at 15:21 Comment(5)
@Alnitak, when did the deferred objects thing get introduced? I haven't seen it before. Also, it seems slightly messy, since the code that defines what callback to use is in a different location than the actual AJAX call.Levitate
it was introduced in jQuery 1.5 and it's far less messy than using success:. Decoupling the callback from the AJAX is a good thing! See the notes I just added to the end of my answer.Omalley
@Alnitak, I'll have a look. Let's see if I can be convinced :PLevitate
@Alnitak: Is deferred objects always preferred over success callback? Thanks.Utu
@Utu IMHO, yes, very much preferred. If your code had been using $.get() for example, it would have been impossible to add an error: handler because $.get doesn't support it. However you can add a .fail to the deferred result of $.get.Omalley
O
205

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.

function getData() {
    return $.ajax({
        url : 'example.com',
        type: 'GET'
    });
}

function handleData(data /* , textStatus, jqXHR */ ) {
    alert(data);
    //do some stuff
}

getData().done(handleData);

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:

// a trivial timer, just for demo purposes -
// it resolves itself after 5 seconds
var timer = $.Deferred();
setTimeout(timer.resolve, 5000);

// add a done handler _and_ an `error:` handler, even though `getData`
// didn't directly expose that functionality
var ajax = getData().done(handleData).fail(error);

$.when(timer, ajax).done(function() {
    // this won't be called until *both* the AJAX and the 5s timer have finished
});

ajax.done(function(data) {
    // you can add additional callbacks too, even if the AJAX call
    // already finished
});

Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.

Omalley answered 7/2, 2013 at 15:22 Comment(5)
@Cerbrus see the new example, and then consider how you'd do it without deferred objectsOmalley
@jbl deferred objects are fantastic. I normally downvote any answer that promotes use of success: because deferreds just work so much better.Omalley
@Cerbrus that's exactly how it's supposed to be interpreted. Suggest you search here for user:6782 deferred for lots more examples.Omalley
How could one utilise this with a form submit event?Sarsaparilla
That alert though... I'd personally use console.log(data) or if it's an array: console.table(data) :)Fossil
L
96

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

Levitate answered 7/2, 2013 at 15:21 Comment(5)
@Alnitak, when did the deferred objects thing get introduced? I haven't seen it before. Also, it seems slightly messy, since the code that defines what callback to use is in a different location than the actual AJAX call.Levitate
it was introduced in jQuery 1.5 and it's far less messy than using success:. Decoupling the callback from the AJAX is a good thing! See the notes I just added to the end of my answer.Omalley
@Alnitak, I'll have a look. Let's see if I can be convinced :PLevitate
@Alnitak: Is deferred objects always preferred over success callback? Thanks.Utu
@Utu IMHO, yes, very much preferred. If your code had been using $.get() for example, it would have been impossible to add an error: handler because $.get doesn't support it. However you can add a .fail to the deferred result of $.get.Omalley
R
15

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.

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

Roselani answered 7/2, 2013 at 16:0 Comment(0)
T
6

Try rewriting your success handler to:

success : handleData

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:

object data
string textStatus
jqXHR jqXHR
Trophoplasm answered 7/2, 2013 at 15:22 Comment(0)
B
5

I would write :

var handleData = function (data) {
    alert(data);
    //do some stuff
}


function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}
Baecher answered 7/2, 2013 at 15:22 Comment(0)
S
2

You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )

Samualsamuel answered 7/2, 2013 at 15:22 Comment(1)
Somehow had to look for a while to find those default parameters. Thanks!Long
C
2

after few hours play with it and nearly become dull. miracle came to me, it work.

<pre>


var listname = [];   


 $.ajax({
    url : wedding, // change to your local url, this not work with absolute url
    success: function (data) {
       callback(data);
    }
});

function callback(data) {
      $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
             //   $('#displayImage1').append( "<img src='" + wedding + val +"'>" );
                 listname.push(val);
            } 
        });
}

function myfunction() {

alert (listname);

}

</pre>
Concerted answered 21/8, 2016 at 5:34 Comment(1)
you do not need to put another function call for success. you can directly say success : callback jquery will trigger your function called callback with the data parameter in it.Module
J
-1

In your component i.e angular JS code:

function getData(){
    window.location.href = 'http://localhost:1036/api/Employee/GetExcelData';
}
Jalisajalisco answered 5/6, 2018 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.