简体   繁体   中英

Cant get value from ajax request to be save in variable outside the success

Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.

When I return the value it always comes up undefined when I alert() inside it shows the proper values.

function getItemInfo(itemHashPass) {

    $.ajax({
        url: 'index.php//Welcome/getItem', //This is the current doc
        type: "POST",       
        data: 'iHash='+itemHashPass,
        dataType: "json",
        async: false,
        success: function(data){

          return data.Response.data.inventoryItem.itemName;

        }
    });  

}

I've also tried

function getItemInfo(itemHashPass) {
  var tmp = null;
  $.ajax({
    url: 'index.php//Welcome/getItem', //This is the current doc
    type: "POST",       
    data: 'iHash='+itemHashPass,
    dataType: "json",
    async: false,
    success: function(data){

      tmp = data.Response.data.inventoryItem.itemName;

    }
 });  
 return tmp;
}

Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like

   function yourBusinnesLogicFunction() {
       ...
       getItemInfo("password_hash_value").done(
          function(data){
              alert(data.Response.data.inventoryItem.itemName);
          }
       )
    }

    function getItemInfo(itemHashPass) {
      var tmp = null;
      return $.ajax({
        url: 'index.php//Welcome/getItem', //This is the current doc
        type: "POST",       
        data: 'iHash='+itemHashPass,
        dataType: "json",
        async: false,
       })
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM