Why doesn't this work
I have an ajax function via jquery inside an object, and for some reason it's not seeing the other functions in the object inside the callback function.
function object () {
this.test = function () { alert ("test") }
this.makeQuery = function() {
$.ajax( {
url: stuff,
dataType: "xml",
success: function (data) { makeData(data) } } )
}
this.makeData = function (data) {
this.test(); // Error "this.test() is not a function"
}
}
The reason is because callback functions are called with a different "this". In the case of the jQuery.ajax call, the "this" function is the jqXHR object http://api.jquery.com/Types/#jqXHR. So if you want to pass the "this" object into the callback you must capture it in the scope and the reference the captured variable. Like this (if I fix all your syntax errors):
function myFunction() {
var that = this;
this.test = function () { alert ("test") };
this.makeQuery = function() {
jQuery.ajax({
type: 'post',
url: 'someUrl',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
that.makeData(data);
},
error: function (jqXHR, textStatus, textError) {
}
});
};
this.makeData = function(data) {
this.data = data
this.test(); // Error "this.test() is not a function"
};
}
var m = new myFunction();
m.makeQuery();