0

I am fairly new to Angular.JS development but have had experience in the past with using PHP, HTML and JS so I am currently building a web application with Angular.JS as the frontend and PHP Slim as the API backend. I have been successful in implementing token-based authentication with Angular.JS $http.post for one of my calls but cannot seem to get the desired result in another $http.post request, which does not require the token authentication.

REQUEST 1 - Angular.JS (WORKING):

  function ($scope, $http, $location) {
  console.log("REACHED");

  $scope.master = {};
  $scope.activePath = null;

  $scope.New_Customer = function(customer, AddNewForm) {
      console.log(customer);
      console.log("2: " + JSON.stringify(customer));

      console.log("SCOPE: " + customer.status);

      $http({
        method: "post",
        url: "v1/customers",
        headers: {
            'authorization': token,
            'Content-Type': 'application/x-www-form-urlencoded'
            },
        data: $.param({first_name: customer.first_name, last_name: customer.last_name, email: customer.email, mobile_number: customer.mobile_number, home_number: customer.home_number, address_line1: customer.address_line1, address_line2: customer.address_line2, city: customer.city, postalcode: customer.postalcode, 'status': customer.status})
        }).success(function(result){
          console.log(result);
          $scope.reset();
          $scope.activePath = $location.path('#/Customers');
        });

      $scope.reset = function() {
          $scope.customer = angular.copy($scope.master);
      };

      $scope.reset();
  };
}

PHP (WORKING)

$app->post('/customers', 'authenticate', function() use ($app) {
        // check for required params
        verifyRequiredParams(array('first_name'));

        $response = array();
        $first_name = $app->request->post('first_name');
        $last_name = $app->request->post('last_name');
        $email = $app->request->post('email');
        $mobile_number = $app->request->post('mobile_number');
        $home_number = $app->request->post('home_number');
        $address_line1 = $app->request->post('address_line1');
        $address_line2 = $app->request->post('address_line2');
        $city = $app->request->post('city');
        $postalcode = $app->request->post('postalcode');

        global $user_id;
        $db = new DbHandler();

        // creating new customer
        $customer_id = $db->createCustomer($user_id, $first_name, $last_name, $email, $mobile_number, $home_number, $address_line1, $address_line2, $city, $postalcode);

        if ($customer_id != NULL) {
            $response["error"] = false;
            $response["message"] = "Customer created successfully";
            $response["customer_id"] = $customer_id;
            echoRespnse(201, $response);
        } else {
            $response["error"] = true;
            $response["message"] = "Failed to create customer. Please try again";
            echoRespnse(200, $response);
        }            
    });

However, for my login script, the data does not appear to be reaching the PHP file where the $http.post request always returns 'null' in the console.

REQUEST 2 - Angular.JS (NOT WORKING)

  function ($scope, $http, $location) {
  console.log("REACHED");

  $scope.Login = function(customer, LoginForm) {
      console.log(customer);
      console.log("2: " + JSON.stringify(customer));

      console.log("SCOPE: " + customer.email);

  $http({
    url: "v1/login",
    method: "POST",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({email: customer.email, password: customer.password})
}).success(function(data, status, headers, config) {
    $scope.data = data;
    console.log($scope.data);
}).error(function(data, status, headers, config) {
    $scope.status = status;
    $scope.data = data;
    console.log($scope.status + " " + $scope.data);
});  
  };
}

PHP (NOT WORKING)

$app->post('/login', function() use ($app) {

        // check for required params
        verifyRequiredParams(array('email', 'password'));

        $response = array();
        $email = $app->request()->post('email');
        $password = $app->request()->post('password');

        $db = new DbHandler();
        // check for correct email and password
        if ($db->checkLogin($email, $password)) {
            // get the user by email
            $user = $db->getUserByEmail($email);

            if ($user != NULL) {
                $response["error"] = false;
                $response['name'] = $user['name'];
                $response['email'] = $user['email'];
                $response['apiKey'] = $user['api_key'];
                $response['createdAt'] = $user['created_at'];
            } else {
                // unknown error occurred
                $response['error'] = true;
                $response['message'] = "An error occurred. Please try again";
            }
        } else {
            // user credentials are wrong
            $response['error'] = true;
            $response['message'] = 'Login failed. Incorrect credentials';
        }

        echoRespnse(200, $response);
    });

Console log:

app.js:148 REACHED
app.js:148 REACHED
/contacts_app_2/#/Login:1 POST http://localhost/contacts_app_2/ 412 (Precondition Failed)
Navigated to http://localhost/contacts_app_2/
app.js:148 REACHED
app.js:148 REACHED
app.js:151 Object {email: "[email protected]", password: "testpassword123"}
app.js:152 2: {"email":"[email protected]","password":"testpassword123"}
app.js:154 SCOPE: [email protected]
app.js:167 0 null
Navigated to http://localhost/contacts_app_2/
app.js:148 REACHED
app.js:148 REACHED

I cannot seem to figure out why my first request (to create a new customer works) yet to login does not work. Any help with this would be greatly appreciated as I have spent time looking through the forums for other answers but have not yet found a way to resolve this issue.

8
  • Why not print out some log before your echoRespnse(200, $response);. Commented Jun 25, 2016 at 1:32
  • I have put in some PHP echos throughout the PHP function but none of them appear to be getting called in the console Commented Jun 25, 2016 at 10:24
  • I suppose it's the problem or your route. Try to make the request via any tools, like Advanced REST Client in Chrome, to test whether the url works or not. Commented Jun 26, 2016 at 10:56
  • 1
    I don't feel like it's the problem of AngularJS code. Have a look at the network logging in your browser's developer tools. Commented Jun 26, 2016 at 11:50
  • 1
    My suggestion is, click on that error line, it will shows the detailed information of the request, the url, the header, the parameter, and the possible error reason. Commented Jun 27, 2016 at 3:25

1 Answer 1

1

Generally, AJAX requests are failed for these reason:

  1. Mistaken url or method
  2. Cors request
  3. Blocked connection

Since you have checked the DevTools and make sure it is not the first one, and you are using the same domain. Let discuss about the third one.

Blocked connection can be debugged by chrome://net-internals/#events. It happends for reasons like disconnected network, firewall issue. The second one is sometime very confusing, which I guess your are facing. I suppose you are blocked by your plugin like AdBlock.

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

1 Comment

Thank you for providing that information but I disabled adblock and had a look through the events where I couldn't see anything out of the ordinary. I instead went on and tried doing exactly the same in: IE, Firefox & Edge - all of which had no problems at all with the code so (as you have said) something in Chrome is blocking this.

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.