Reputation:
function Profiles() { };
Profiles.prototype.test = function() {
var opt = {
url: __profileurl__+'getall/', type: 'get', dataType:'json',
success:function(response){
return response;
}
};
$.ajax(opt);
};
var profile = new Profiles();
var r = profile.test();
// returns undefined... expected output should be the response from the request.
Upvotes: 1
Views: 819
Reputation: 12052
You can do it with an async request, but it's generally a Bad Thing
Something like the following oughta return the data.
function Profiles() { };
Profiles.prototype.test = function() {
var returnedResponse;
var opt = {
async: false,
url: __profileurl__+'getall/', type: 'get', dataType:'json',
success:function(response){
returnedResponse = response;
}
};
$.ajax(opt);
return returnedResponse;
};
BUT
Unless you really really need to be able to use the return value from test straight away, you'll be much better off passing a callback into test. Something like
Profiles.prototype.test = function(callback) {
var opt = {
url: __profileurl__+'getall/', type: 'get', dataType:'json',
success:function(response){
callback(response);
}
};
$.ajax(opt);
};
var profile = new Profiles();
profile.test(function(data) {
// do something with the data
});
Upvotes: 3
Reputation: 139
try setting the the AJAX request to synchronous.
url: profileurl+'getall/', type: 'get', dataType:'json', async: false
Upvotes: 0
Reputation: 41232
Because you function is not returning anything, "success" is definition for callback function and you cannot use it to return values from your main function. More over since ajax call is asynchronous the callback function will be called after you main function ends.
You can define global variable initially instantiated to null and in success you will assign it to that variable and then you can check whenever it's null or not. You can do it more sophisticated, by redesigning your object to have the field which will be responsible for response and method which will return you it. But still you have a problem since call is asynchronous and javascript doesn't have any synchronization, so you will need to find workaround using setTimeout function.
PS. Much better is to put the logic you need in that callback function, or maybe in that callback function make another call, there your will process your data.
Upvotes: 0
Reputation: 4972
You cannot "return" a response its an asynchronous response . I guess you can put a while loop around the call and wait for response if you dont want the execution to move further without getting the response back .
Upvotes: 0