0

So I have bee trying to make a simple login page using Angular 10 as frontend and PHP as a server-side backend language(no PHP frameworks used here).

Here is my login.service.ts file:


    import { Injectable } from '@angular/core';
    import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams} from '@angular/common/http';

    //import { User } from '../shared/user.model';
    import { throwError } from 'rxjs';
    //import { map, tap } from 'rxjs/operators'

    export interface LoginResponse{
        id:bigint;
        username:string;    
        password:string
        user_date:string    
        show_user:number; 
        save_time:string
    }

    @Injectable({
        providedIn:'root'
    })


    export class LoginService{

        constructor(private http: HttpClient){}


        loginUser(username: string, password:string){
        
            const user = JSON.stringify( { "user" : {"username":username, "password" : password} });
            return this.http.post<any>(
                "http://localhost/calibration/login.php",
                user,
                {
                    headers: new HttpHeaders({'Content-Type':'text/plain'})
                }
            );
        }

        handleError(errorResponse:HttpErrorResponse){
            console.log(errorResponse);
            return throwError("Something Went Wrong");
        }
            
    }

and here is my login.php file:

        <?php  
        session_start();
        require_once("connection.php");
        var_dump($conn);
        try  
        {  
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
        var_dump($_POST);
        if(isset($_POST["user"]))  
        {     
                $obj = json_decode($_POST["user"]);
                $query = "SELECT * FROM user_master WHERE username = ? AND password = ?";  
                $statement = $conn->prepare($query); 
                $statement->bind_param(1, $username, $_POST['username']);
                $statement->bind_param(2, $password, $_POST['password']);
                $username = $obj->username;
                $password = $obj->password;
                $statement->execute();  
                $count = $statement->rowCount();  
                if($count > 0)  
                {  
                        $_SESSION["username"] = $_POST["username"];  
                        //header("location:login_success.php");  
                }  
                else  
                {  
                        $message = '<label>Wrong Data</label>';  
                }  
        }
        }  
        catch(PDOException $error)  
        {  
        $message = $error->getMessage();  
        }

    ?>   

Here is the response I received after trying to run the PHP file through the login.service.ts:

            {
        "headers": {
        "normalizedNames": {},
        "lazyUpdate": null
        },
        "status": 200,
        "statusText": "OK",
        "url": "http://localhost/calibration/login.php",
        "ok": false,
        "name": "HttpErrorResponse",
        "message": "Http failure during parsing for http://localhost/calibration/login.php",
        "error": {
        "error": {},
        "text": "object(PDO)#1 (0) {\n}\narray(0) {\n}\n  "
        }
    }

    text: "object(PDO)#1 (0) {\n}\narray(0) {\n}\n

Any help?

Update: Made some changes to the code to reflect some of the recommendations given below

dhesikanC
  • 1
  • 7
  • The second parameter to [http.post](https://docs.angularjs.org/api/ng/service/$http#put) should be a string, currenlty you are sending an object? Try to send something like: `username=user&password=secret` – Luuk Nov 16 '20 at 16:54
  • Have you tried to check `if(isset($_POST["username"]))` instead `$_POST['login']` ? – Robson Sousa Nov 16 '20 at 16:58
  • @RobsonSousa Tried it, the error still persists. – dhesikanC Nov 16 '20 at 18:19
  • @Luuk Like sending the response data in a 'string' format? – dhesikanC Nov 16 '20 at 18:19
  • Yes, like sending the body in text format (as a string). – Luuk Nov 16 '20 at 18:25
  • I'm not sure about these params into execute function. You could use bind_param function before execute function. Like this: `$statement->bind_param("ss", $_POST["username"], $_POST["password"]); $statement->execute();` – Robson Sousa Nov 16 '20 at 18:37
  • You should also add `vardump($_POST)` at the start of your PHP script to see the contents of the posted vars. – Luuk Nov 16 '20 at 19:29
  • @Luuk So I should use the header 'content-type' : 'text', right? – dhesikanC Nov 16 '20 at 19:44
  • You should set the headers according to one of the options mentioned here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST – Luuk Nov 17 '20 at 07:06
  • @Luuk I made some changes, its still not working. The error still persists – dhesikanC Nov 17 '20 at 13:22
  • @RobsonSousa Made some changes to the PHP file as you suggested, its still not working. – dhesikanC Nov 17 '20 at 13:28
  • Sorry, my knowledge of Angular is too thin to help you further. Maybe it helps to invest some time in learning the technical details of POST, like is explained (i.e.) in [this](https://stackoverflow.com/questions/15603561/how-can-i-debug-a-http-post-in-chrome) question. – Luuk Nov 17 '20 at 17:02
  • @dhesikanC no, you didn't. In the code above you are using this: `$statement->bind_param(1, $username, $_POST['username']);` with wrong parameters. Please try exactly like this: `$statement->bind_param("ss", $_POST["username"], $_POST["password"]);` with the two parameters at the same time. – Robson Sousa Nov 20 '20 at 03:06

0 Answers0