skip to Main Content

I am able to get result from ajax API Call and want to store result into var, but the result does’t store into var. Please help me to achieve this. Below is the code for ajax response:-

var Name = '';

function webservice_returnResult(apiURL, id) {
    return $.ajax({
        type: 'GET',
        url: baseurl + '/' + apiURL,
        data: { "Id": id },
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function (response) {
            //Data = response;
        }
    });
}
 
    webservice_returnResult('api/sample/GetById', Id).done(function (result) {
        Name = result.Name;
    });
  
    console.log(Name);

result.Name does’t save into var Name.

2

Answers


  1. Could be a scope problem here. The ‘this’ can be bind, but I think when you try it with an arrow function it can resolve the issue.

    webservice_returnResult('api/sample/GetById', Id).done((result) => {
        Name = result.Name;
    });
    
    Login or Signup to reply.
  2. To use the result, you must wait for the request to finish

    function fetchNameFromAPI(apiURL, id) {
        return webservice_returnResult(apiURL, id)
            .done(function (result) {
                return result.Name;
            });
    }
    
    fetchNameFromAPI('api/sample/GetById', Id)
        .done(function (result) {
            Name = result.Name;
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search