al_kasih_empatix
al_kasih_empatix

Reputation: 127

return data inside function from http post

I want to get data pass from a function, the data successfully return inside the success response. However I can't return the data from the function itself.

function getStatusPublished(dating, product) 
{
    var datas = "";

    var success = function(response, status, headers, config){
      datas = response;
    }

    var error = function(error, status, headers, config){
      datas = "error";
    }

    var cdnss = "htttp://application_ajax";
    $http.post(cdnss+"&pblishDateVacan="+dating+"&ProjectID="+product)
    .success(success).error(error);

    console.log(datas);
}

In the console.log, it just said undefined.

Please help. Thanks.

Upvotes: 1

Views: 3823

Answers (1)

georgeawg
georgeawg

Reputation: 48968

The $http.post method returns a promise; not data.

To return a promise, simply use a return statement.

function getStatusPublished(dating, product) {
    var url = "htttp://application_ajax";
    var postData = {};
    var params = {
      pblishDataVacan: dating,
      ProjectId: product
    };
    var config = { params: params };
    var promise = $http.post(url,postData,config);
    //return promise
    return promise;
}

To get the data from the promise, use the .then method:

var promise = getStatusPublished(d, p);

promise.then( function(response) {
    $scope.data = response.data;
    return response.data;
}).catch ( function(response) {
    console.log(response.status);
    throw response;
}); 

Upvotes: 1

Related Questions