Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10561

How to return value from an ajax call function

I have a function

function GetITStaffList(){
    var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0";
    $jqLibrary.get(go_path,
        {}, function(data)
        {
            var parseData = JSON.parse(data);
            console.log("GetPendingAndInProgressComplainsByGeneratorId : ", parseData);

            return parseData;
        });
}

I am calling this somewhere in the code like this

var ITStaffList = GetITStaffList();
MakeDropDownITStaff(ITStaffList);

But the problem is each time it is returning null. I know that I have to use callback and something like a promise but I don't how to fit this thing in my context. How do I write a reusable function with ajax call that returns data on demand.?

Upvotes: 0

Views: 247

Answers (1)

Charlie
Charlie

Reputation: 23818

Return a promise instead.

function GetITStaffList(){

    return new Promise(function(resolve){

       var go_path = "Server/ITComplains.php?action=GetITStaffList&vars=0";
       $jqLibrary.get(go_path,
           {}, function(data)
           {
               var parseData = JSON.parse(data);
               console.log("GetPendingAndInProgressComplainsByGeneratorId : ", parseData);

            resolve(parseData);    //Notice this
        });
    })
}

Now you can call the function and wait for data.

GetITStaffList().then(function(data){
    console.log(data)
})

Upvotes: 1

Related Questions