jQuery $.ajax(), pass success data into separate function
ajax, callback, javascript, jquery
Solution
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>
Problem
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); } }); } ```