[javascript] jQuery ajax success callback function definition

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
}

This question is related to javascript jquery ajax

The answer is


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>

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.


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

In your component i.e angular JS code:

function getData(){
    window.location.href = 'http://localhost:1036/api/Employee/GetExcelData';
}

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


I would write :

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


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios