1

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.

5
  • Your server side script will need to return an error code. Angular can't know your "ERROR" string is an error as long as it's told the request is "200 OK". php.net/manual/en/function.http-response-code.php Commented Jan 17, 2016 at 10:28
  • You should also note that the .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 keys data, status, headers, config, and statusText exactly the same as those exposed by .success() and .error(). Commented Jan 17, 2016 at 10:34
  • OK. I understand. How can i make my server side script to return an error code (or correct error-message) if the token does not exist? Can you please post an example here? thx Commented Jan 17, 2016 at 10:37
  • @BobChao87, thx, i read a lot about the .then-function, especially to get the right order of asynchronous calls. But .then() will not be helpful with my "ERROR" response, or i am wrong ? Commented Jan 17, 2016 at 10:46
  • It won't help with the error response, but it will help future proof your code. You might want to check out http_response_code() or even header() if you are using an older version of PHP for actually changing the function that Angular uses to read your return. Commented Jan 17, 2016 at 19:45

1 Answer 1

2

By default angular content-type is application/json. i think your overriding of header is not working, may be because of data before headers you sent.

   var request = $http({
   method: "post",
   url: constantService.url + 'login.php',
   data : data, // here key : value pair is missing
   headers: {
       'Content-Type': 'application/x-www-form-urlencoded'
   }
   });

so angular thinks you providing a json response and parsing it as json. so when your response is ERROR is just trying to parse as json and throwing parse error.

and about callbacks. the error function will not fired until you sent error code or browser ditect a error. here is the error codes link

in your case both ERROR and json_encode(token) will fire the success function. so you should process in success function also as error function. you might do in your php file

if(/*success condition */){
    $json = array('status'=>'success','token'=>$token);
   }else{
    $json = array('status'=>'error','reason'=>'failed to generate token or somthing');
   }
echo json_encode($json);

and in your success function

request.success(function(response) {
  if(response.status === 'success' ){
   $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();
}else{
   console.log(response.message);//you can do as you error function
}
  });

and don't forget to remove the headers setting if you don't need it. or if you need it do a JSON.parse(response) in top of success function.

Sign up to request clarification or add additional context in comments.

1 Comment

@fishermann. thx a lot. This was exactly the problem. I did your suggestion and it works fine. You saved my day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.