0

I made a function for managing data sending to server side. I want to return response of $http when it success.

My controller: (When I call the function)

var myResponse = sendData(inputValueArray, url, onSuc, onErr, $http);
// Nothing happen here:
alert(myResponse);

My function for sending data:

function sendData(inputArray, url, onSuccess, onErr, $http) {
var serverResponse = "";
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http({
        method: 'POST',
        url: url,
        data: {
          myData: inputArray
        },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
.success(function(response) {
    if (response.res == true) {
        onSuccess();
        serverResponse = response;
    }
    else {
        onErr();
    }
})
.error(function(data, status, headers, config) {
    onErr();
});
return serverResponse;

}
Vahid Najafi
  • 4,654
  • 11
  • 43
  • 88

1 Answers1

1

You are returning serverResponse before it has any data from the call back. Instead, try something like this:

function sendData(inputArray, url, onSuccess, onErr, $http) {
  var serverResponse = "";
  $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  return $http({
        method: 'POST',
        url: url,
        data: {
          myData: inputArray
        },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
}

And then you use it like this

sendData
.success(function(response) {
    if (response.res == true) {
        onSuccess();
        serverResponse = response;
        alert(serverResponse);   // ************
    }
    else {
        onErr();
    }
})
.error(function(data, status, headers, config) {
    onErr();
});
Simon H
  • 20,332
  • 14
  • 71
  • 128
  • I want to get the response to do a lot of things with it in `controller`. So not simply an alert. Also it's more flexible for me. Thanks :) – Vahid Najafi Nov 26 '15 at 16:38