Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  39] [ 3]  / answers: 1 / hits: 133473  / 15 Years ago, mon, march 8, 2010, 12:00:00

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);
}
});
}

More From » jquery

 Answers
127

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>

[#97394] Friday, March 5, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;