I'm using AngularJS $http.post to call PHP in my login-function. The PHP gives back a token and if not exists the word "ERROR".
PHP-Code:
....
echo json_encode($token);
} else {
echo "ERROR";
}
Controller.js:
var request = $http({
method: "post",
url: constantService.url + 'login.php',
data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
request.success(function(response) {
$localstorage.set("token", JSON.stringify(response));
var showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: ' successful token-based login',
template: response
});
alertPopup.then(function(res) {
console.log(res);
$state.go('home');
});
};
showAlert();
});
request.error(function(data, status, headers, config) {
console.log('An error occurred ');
var showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error',
template: 'check your login credentials'
});
alertPopup.then(function(res) {
});
};
showAlert();
});
When i get back a correct token it's working without problems. When i get back the word "ERROR" ( no token exists ) i get the following error in chrome inspector:
**SyntaxError: Unexpected token E**
at Object.parse (native)
at fromJson (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9764:14)
at defaultHttpResponseTransform (http://localhost:8100/lib/ionic/js/ionic.bundle.js:17278:16)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:17363:12
at forEach (http://localhost:8100/lib/ionic/js/ionic.bundle.js:9022:20)
at transformData (http://localhost:8100/lib/ionic/js/ionic.bundle.js:17362:3)
at transformResponse (http://localhost:8100/lib/ionic/js/ionic.bundle.js:18088:23)
at processQueue (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21888:27)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:21904:27
at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:23100:28)
Whats the correct way to give back the word "ERROR" an handle it in my response.error-function ? Is this a JSON-encoding/decoding problem ? Tried all to solve this issue but without success. THX.
.success(successFunc)and.error(errorFunc)methods have been deprecated. You should use the.then()method which can just take those functions as arguments; i.e..then(successFunc, errorFunc). The functions only expose one variable, but that variable is an object with keysdata,status,headers,config, andstatusTextexactly the same as those exposed by.success()and.error().http_response_code()or evenheader()if you are using an older version of PHP for actually changing the function that Angular uses to read your return.