Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        }
    });
}
like image 256
Nic Hubbard Avatar asked Mar 08 '10 17:03

Nic Hubbard


People also ask

What is difference between success and complete in AJAX?

success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.


2 Answers

Works fine for me:

<script src="/jquery.js"></script> <script> var callback = function(data, textStatus, xhr) {     alert(data + "\t" + textStatus); }  var test = function(str, cb) {     var data = 'Input values';     $.ajax({         type: 'post',         url: 'http://www.mydomain.com/ajaxscript',         data: data,         success: cb     }); } test('Hello, world', callback); </script> 
like image 102
Mike Thomsen Avatar answered Nov 15 '22 08:11

Mike Thomsen


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);
    }
like image 32
iPath ツ Avatar answered Nov 15 '22 08:11

iPath ツ