I have two js files named main.js and utility.js. I am calling the ajax from main.js and i want the json response in main.js.
Main.js:
var details= getUIContent();
Utility.js:
function getUIContent(){
$.ajax({
type: "POST",
url: "http://abc.com/portal",
async: false,
success: function(message){
channels = message.data.length;
alert('the channel length'+channels);
return message;
}
});
}
I am getting the response in utility.js. The problem is i am not able to get the response in main.js. It is giving the error like undefined.
Can anyone help me
It seems message.data is not returned from the server. Please verify your server side code to ensure data is added to your response or not.
As I said you cannot return value from a async method like ajax()
.
The solution here is to use a callback method
function getUIContent(callback){
$.ajax({
type: "POST",
url: "http://abc.com/portal",
async: false,
success: function(message){
channels = message.data.length;
alert('the channel length'+channels);
callback(message);
}
});
}
getUIContent(function(details){
//do whatever you want to do with details here
});
Or return a promise from the method
function getUIContent(){
return $.ajax({
type: "POST",
url: "http://abc.com/portal",
async: false,
success: function(message){
channels = message.data.length;
alert('the channel length'+channels);
}
});
}
getUIContent.done(function(details){
//do whatever you want to do with details here
});