Return value from ajax and set that value to a variable

10,549

Solution 1

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
    });

Solution 2

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;
     }
   });
Share:
10,549
rakcode
Author by

rakcode

Web Designer/Developer, Android Developer & Graphic Designer who very much interested in Learning New Web Technologies and Code some templates for learning Purposes. FOR FUN: YouTube, Facebook, Whatsapp, Movies, Songs, etc....

Updated on June 05, 2022

Comments

  • rakcode
    rakcode almost 2 years

    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?

  • karthick
    karthick almost 7 years
    it only assigns it doesn't return
  • Gopinath
    Gopinath almost 7 years
    why you need to return? The question is to assign the value to obj
  • George
    George almost 7 years
    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 :)
  • Thomas Maddocks
    Thomas Maddocks almost 7 years
    The problem with this, how does anyone know when obj contains the response? The success handler should take a callback which accepts the response once the AJAX call has completed.
  • rakcode
    rakcode almost 7 years
    this method works if u use async : false
  • EGP
    EGP over 4 years
    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.
  • Kirill
    Kirill over 4 years
    @EGP, I suggest you to read about async\await method on this link stackoverflow.com/questions/14220321/… I think it will solve your problem.
  • EGP
    EGP over 4 years
    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.