[javascript] jQuery $.ajax(), pass success data into separate function

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.

Here is what I was thinking would work, but it is not:

testFunc = function(str, callback) {
    // Send our params
    var data = 'some data to send';
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: data,
        success: callback
    });
}

Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:

testFunc('my string data', function(data){
    alert(data);
});

I am wanting this to be the same as:

testFunc = function(str, callback) {
    // Send our params
    var data = 'some data to send';
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: data,
        success: function(data) {
            alert(data);
        }
    });
}

This question is related to javascript jquery ajax callback

The answer is


this is how I do it

function run_ajax(obj) {
    $.ajax({
        type:"POST",
        url: prefix,
        data: obj.pdata,
        dataType: 'json',
        error: function(data) {
            //do error stuff
        },
        success: function(data) {

            if(obj.func){
                obj.func(data); 
            }

        }
    });
}

alert_func(data){
    //do what you want with data
}

var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);

I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)


Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:

function GetProcedureById(procedureId)
{
    var includeMaster = true;
    pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: pString,
        datatype: "json",
        dataFilter: function(data)
        {
            var msg;
            if (typeof (JSON) !== 'undefined' &&
                    typeof (JSON.parse) === 'function')
                msg = JSON.parse(data);
            else
                msg = eval('(' + data + ')');
            if (msg.hasOwnProperty('d'))
                return msg.d;
            else
                return msg;
        },
        url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
        success: function(msg)
        {
            LoadProcedure(msg);
        },
        failure: function(msg)
        {
            // $("#sometextplace").text("Procedure did not load");
        }
    });
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
    if (jdata.length < 10)
    {
        $("select#cptIcdProcedureSelect").attr('size', jdata.length);
    }
    else
    {
        $("select#cptIcdProcedureSelect").attr('size', '10');
    };
    var options = '';
    for (var i = 0; i < jdata.length; i++)
    {
        options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
    };
    $("select#cptIcdProcedureSelect").html(options);
};

You can use this keyword to access custom data, passed to $.ajax() function:

    $.ajax({
        // ... // --> put ajax configuration parameters here
        yourCustomData: {param1: 'any value', time: '1h24'},  // put your custom key/value pair here
        success: successHandler
    });

    function successHandler(data, textStatus, jqXHR) {
        alert(this.yourCustomData.param1);  // shows "any value"
        console.log(this.yourCustomData.time);
    }

In the first code block, you're never using the str parameter. Did you mean to say the following?

testFunc = function(str, callback) {
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: str,
        success: callback
    });
}

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

Examples related to callback

When to use React setState callback How to send an HTTP request with a header parameter? javascript function wait until another function to finish What is the purpose of willSet and didSet in Swift? How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? Aren't promises just callbacks? How do I convert an existing callback API to promises? How to access the correct `this` inside a callback? nodeJs callbacks simple example Callback after all asynchronous forEach callbacks are completed