I have a ajax call inside a function that returns a json object on success function, i need to set returned data to a variable, searched for answer but i couldn't find any useful answers.
Method 1:
im calling a function and setting returned value to a variable like this
var obj = ajaxCall();
my code is like
function ajaxCall(){
var result;
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
result = data;
}
});
return result;
}
if i log the data inside success callback my json is similar to this
[{ collection: "Super Hero", img:"http://img_url.jpg",
heros: [{ id: "111", text: "Iron Man" },
{ id: "123", text: "Superman" },
{ id: "124", text: "Batman" }]
}]
but it is not returning value, instead of value it returns empty string, because that return function doesn't wait for ajax success function.
Method 2:
I have tried with calling function from success and returning value from that funcion, like this
function ajaxCall(){
var result;
$.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
callBack(data);
}
});
function callBack(data){
return data;
}
return callBack();
}
in this case the function is returning the value but only another array inside main array (heros) only, not outside variables, how to fix it?
i tried above methods, and i have seen something like below (not sure where i have seen this) to set ajax result directly to variable
function ajaxCall(){
var result= $.ajax({
url: url_of_my_php_file,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function(data) {
// it returns json Object "data"
result = data;
}
},(0);
}
is this method is valid?
if not, then is there any way to get that string to result variable and return it to obj?
Update:
I have tried this link, but that method is not working for me, if it is not working for me then how it is a copy?