2

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?

rakcode
  • 2,256
  • 4
  • 19
  • 44

2 Answers2

10

Use callbacks

function ajaxCall(callback){
   $.ajax({
       url: url_of_my_php_file,
       dataType: 'json',
       type: 'GET',
       contentType: 'application/json',
       success: callback
   });
}

ajaxCall(result => {
    //do something with result
})

Or Promises

function ajaxCall(callback){
    return new Promise((resolve, reject) => {
        $.ajax({
            url: url_of_my_php_file,
            dataType: 'json',
            type: 'GET',
            contentType: 'application/json',
            success: resolve,
            error: reject
        });
    });
}

ajaxCall()
    .then(result => {
        //do something with result
    })
    .catch(err => {
        //or err
    });
Kirill
  • 414
  • 7
  • 16
  • 3
    So far the only correct one on this question, congrats! FYI you can just do `success: callback` no need to create an anonymous function to call a named one :) – George Jun 15 '17 at 07:35
  • option #1, callbacks did not work for me. If I put an alert on result, I see the results. But I need to assign it to a variable to persist and that doesn't work. Variable remains empty. – EGP Jan 22 '20 at 14:53
  • 1
    @EGP, I suggest you to read about async\await method on this link https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call I think it will solve your problem. – Kirill Jan 23 '20 at 16:18
  • Googling suggests that async/await is not supported in IE, which is a requirement. I solved it by writing all the data to the DOM instead of persisting in a variable. It wasn't too huge a dataset and no other reason why it would be bad to make it available in the source. I could possibly see async/await being useful in other situations, though. – EGP Jan 24 '20 at 20:16
1

Try this

var obj;
  $.ajax({
      url: url_of_my_php_file,
      dataType: 'json',
      type: 'GET',
      contentType: 'application/json',
      success: function(data) {
      // it returns json Object "data"
      obj = data;
     }
   });
karthick
  • 11,998
  • 6
  • 56
  • 88
Gopinath
  • 21
  • 3