I Am trying to make a simple login check , using angular 4 , php my sql .
Now i am able to send the details to the php , but i am not able to receive the status after it , i have no idea why.
Simply, i want to check if the username and password are correct, then return some json , else , return false result.
Help please.
Angular :
import { Injectable } from '#angular/core';
import { Http, Response ,RequestOptions,Headers} from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
#Injectable()
export class appService {
postResponse:any ;
status;
constructor(private http:Http) { }
insertData() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:80/angularsql/sql.php',JSON.stringify({firstName:'Joe',lastName:'Smith333'}),{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:'') => this.postResponse = res);
}
}
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$data = json_decode( file_get_contents('php://input'),true );
$fname = $data['firstName'];
$lname = $data['lastName'];
$con = new mysqli('localhost','root','','angular');
if($fname=='anan' && $lname=='kassis') {
$sql = "insert into users_tbl(firstName,lastName) values('".$fname."','".$lname."')";
$result = $con->query($sql);
$data = [ "status" => "CORRECT" ];
echo json_encode($data);
}
else {
$data = [ "status" => "wrong details inserted" ];
echo json_encode($data);
}
//echo $result;
?>
I think you should change
subscribe((res:'') => this.postResponse = res);
to
subscribe(res: any =>
{
this.postResponse = res);
console.log(res.status)
}
Here, res will be an object and you can console.log(res.status)
Edit: You cannot have the console.log after the subscribe call, because at this stage the http call has not received a response yet.
Other things to consider:
And probably set json type headers in your php response
header('Content-Type: application/json');
Also, you should use parametrized queries (like PDO) when querying your database
I think this line is the issue:
.subscribe((res:'') => this.postResponse = res);
Change your call into:
insertData(): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:80/angularsql/sql.php', JSON.stringify({
firstName: 'Joe',
lastName: 'Smith333'
}), { headers: headers })
.map(res => res.json())
.catch((error: any) => Observable.throw(
{ message: error.json().message, details: error.json().details }));
}
You should subscribe to the insertData() method. And in your .post() you map the result and you catch the errrors (if any).
Related
I'm new in Angular, and i'm developing a login auth service, but i'm gettin some troubles to make the post data for an backend developed in CodeIgniter.
I'm sending: username and userpassword, to URL: http://192.168.1.162/advance-managemente_2.1/login
Follow my code:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { UserData } from './login/user.model';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
userData: UserData;
getUserDetails(username, userpassword) {
console.log(username, userpassword);
const userdata = JSON.stringify({user: {login: username, password: userpassword}});
const headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
console.log(userdata);
// post these details to API server return user info if correct.
return this.http.post(`http://192.168.1.162/advance-management_2.0/login`, userdata, {headers: headers, observe: 'response'})
.subscribe(res => {
console.log(res);
},
err => {
console.error(err);
});
}
}
And my console:
Note: my variables with username and userpassword is working.
And in codeigniter's backend project is setted these headers:
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
And the function os codeigniter is:
function login(){
$json = $this->input->post('user');
echo json_encode($json);
}
If you observe, my login function have an ECHO with json_encode of i'm sending to her.
But, in console, the body is returning NULL.
I'd like to know what I might be doing wrong, and how to fix it, because it was for him to return a JSON, but it does not seem to be identifying my POST.
Thanks to anyone who can help,
Have a nice day!
I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.
This is my function
test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = [];
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}
And this is an example function on the backend
else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}
So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.
Posting using POSTMAN with this
method=getThis&db=myDatabase
works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.
You could try it that way. It works for me:
First import:
import { map } from "rxjs/operators/map";
Your function:
test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).pipe(
map(res => res.json())
).subscribe(response => {
//Here your code
// 'response' is json
});
}
Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/html'
})
};
this.http.post("API URL", data, httpOptions).subscribe()
PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.
//demo.php
<?php
$data = ['message' => 'Hello world.'];
header("Content-Type: application/json; charset=UTF-8");
//If allow cross domain and not configration in Ngix/Apache
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");
echo json_encode($data);
And please try http access demo.php again.
Here is my (login.service.ts) code:
private pageURL = 'http://localhost/social/src/app/api/ws/react_signup_login/login.php';
user = new UserLogin();
login(value: Object): Observable<any> {
const body = new URLSearchParams();
Object.keys(value).forEach(key => {
body.set(key, value[key]);
});
let headers = new Headers();
headers.append('Content-Type',
'application/x-www-form-urlencoded');
return this._http.post(this.pageURL, this.user.toString(), {
headers: headers
}).map(res => res.json());
}
And this is my login.ts class
export class UserLogin {
username: string;
password: string;
constructor() {
}
}
in (login.component.ts)
user = new UserLogin();
login(value) {
this._loginService.login({value})
.subscribe(
response => this.user = response,
error => console.log(error)
);
}
Finally my (login.php) that I expect the error is here
header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
$_POST = json_decode(file_get_contents('php://input'), true);
$params['username'] = $_POST['username'];
$params['password'] = $_POST['password'];
When I'm trying to (var_dump) the $params I got this:
array(2) {
["username"]=>
NULL
["password"]=>
NULL
}
In your POST Http call you should use your defined URLSearchParams as body and not user, because your user object is empty.
Change your http call code block in login.service.ts from this:
return this._http.post(this.pageURL, this.user.toString(), {
headers: headers
}).map(res => res.json());
to this:
return this._http.post(this.pageURL, body.toString(), {
headers: headers
}).map(res => res.json());
Try to use:
return this._http.post(this.pageURL, value, {
headers: headers
}).map(res => res.json());
Where value is your user object
Here is my problem with my backend which is MySQL. One query is giving me this set of data
{"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz","parti":"Babbleopia","departement":"Sweden","commune":"Täby"}]
A array of arrays , and I wanna access to the nested arrays for my Angular project. I mean this part
[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz","parti":"Babbleopia","departement":"Sweden","commune":"Täby"}]
Here is my component
import { IPaeComponent } from './paeI';
import { NgModel } from '#angular/forms/src/directives';
import { Component, OnInit } from '#angular/core';
import { CandidatService } from './paeServices';
#Component({
selector : 'pae-app',
moduleId : module.id,
templateUrl : 'pae1.html'
})
export class PaeComponent implements IPaeComponent{
prog1 : string ="Programme d'Appui aux Elections";
progName1 : string ="Enquête sur les candidats";
searchbar : string ='';
progEl1 : string ="Listes des candidats ciblés";
candInfo : any [];
filter : string;
candidats : IPaeComponent;
errorMessage : string;
constructor (private _candidatService : CandidatService){
}
ngOnInit(): void {
this._candidatService.getCandidatInfo()
.subscribe(candidats => this.candInfo = candidats,
error => this.errorMessage = <any>error);
}
}
My services:
import { IPaeComponent } from './paeI';
import { Injectable } from '#angular/core';
import { Http, Response , Headers, RequestOptions} from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/do'
import 'rxjs/add/operator/catch'
#Injectable()
export class CandidatService {
private _candidatUrl ='http://localhost/CRUD/api.php/candidat?transform=1';
constructor(private _http : Http){
}
///////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//////////////////////CRUD///////////////////////////
////////////////////////////////////////////////////
///////////////////////////////////////////////////
getCandidatInfo() : Observable<IPaeComponent[]>{
return this._http.get(this._candidatUrl)
.map((response : Response)=><IPaeComponent[]> response.json())
.do(data => console.log('All '+ JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error : Response){
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
addCandidatInfo (body: Object): Observable<IPaeComponent[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this._http.post(this._candidatUrl, body, options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
updateCandidatInfo (body: Object): Observable<IPaeComponent[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this._http.put(`${this._candidatUrl}/${body['id']}`, body, options) // ...using put request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
removeInfo (id:string): Observable<IPaeComponent[]> {
return this._http.delete(`${this._candidatUrl}/${id}`) // ...using put request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
}
And what it looks like when I debug in my browser:
Thanks in advance for your help
Just extract the array from your response:
getCandidatInfo() : Observable<IPaeComponent[]>{
return this._http.get(this._candidatUrl)
.map((response : Response)=><IPaeComponent[]> response.json().candidat) // here
.do(data => console.log('All '+ JSON.stringify(data)))
.catch(this.handleError);
Try this
this._candidatService.getCandidatInfo()
.subscribe(candidats => {
this.candInfo = candidats.candidat;
// if you want get value from particular index
cosnole.log(this.candInfo[0]);
// Or you can iterate loop to get each value
},
error => this.errorMessage = <any>error);
I'm trying to recreate Post JSON from angular 2 to php but it doesn't work as there's nothing in the $_REQUEST variable on php side
The code:
searchHttp({body}: any): Promise<any>
{
let headers = new Headers ({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, method: "post" });
let test_this = {"search": "person"};
return this.http.post(this.post_url, JSON.stringify(test_this), options)
.toPromise()
.then(response =>
{
return response.text();
})
.catch(this.handleError);
}
Is there something I'm missing? I know that posts works with another format because I have that answered in another question.
Also, is http.request better than http.post?
Edit:
After much consultation with Angular/Javascript experts, they believe this is a php issue. So anyone with knowledge of how to accept JSON objects on php side will be gladly welcomed.
angular 2 client side part
ngOnInit() {
let body=Api+'product.php'+'?id=' + this.link_id;
this._callservice.callregister(body)
.subscribe( data => {
this.outputs=data;
},
error => console.log("Error HTTP Post"),
() => console.log("completed") );
}
}
call.service.ts
import {Injectable} from '#angular/core';
import {Router} from '#angular/router';
import {Http, Response, Headers, RequestOptions} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Injectable()
export class AuthenticationService {
constructor(private _http:Http){}
postregister(api:any){
// console.log(api);
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, method: "post"});
return this._http.get(api,options)
.map(res => res.json())
.catch(this.handleError);
}
private handleError (error: Response) {
console.error(error);
return Observable.throw(error.json().error || ' error');
}
}
Server side PHP
make sure on server side you have these three lines in php code.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
Php file:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$servername = "localhost";
$username1 = "root";
$password = "root";
$dbname = "product";
$e=array("error"=>1,"message"=>"Account Already Exists");
$accountCreated = array( "error" =>0,
"data" => array(
"username" => "amit" ,
"password" => "anypassword",
"role"=> "user",
"id" => "anyid" ) );
// Create connection
$conn = mysqli_connect($servername, $username1, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = $_GET["username"];
$Pass = $_GET["password"];
$role= $_GET["role"];
$sql="SELECT COUNT(*) as user FROM users WHERE username = '$username'";
$result = mysqli_query($conn,$sql);
$line = mysqli_fetch_assoc($result);
$count = $line['user'];
if($count!=0)
{
echo json_encode($e);
}
else
{
$sql="INSERT INTO users(username,password,role)VALUES('$username','$Pass','$role')";
$result=mysqli_query($conn,$sql);
$sql="select * from users where username ='$username'";
$result=mysqli_query($conn,$sql);
$line=mysqli_fetch_assoc($result);
{
$accountCreated['data']['username']=$line['username'];
$accountCreated['data']['password']=$line['password'];
$accountCreated['data']['role']=$line['role'];
$accountCreated['data']['id']=$line['id'];
}
echo json_encode($accountCreated);
}
?>
i hope this will work for you .. for json i guess you should pass as options and use json decode for values you get in options.
There doesn't appear to be anything wrong with the Angular code. The issue is in what the PHP is expecting to receive. I am not a PHP expert, but as you've mentioned that it works fine with jQuery, then that indicates that your PHP is expecting a URL-encoded value (as jQuery tends to work with that), not a JSON value.
In other words, what the server is trying to parse is:
search=person
What you are sending is:
{ "search": "person" }
Try something more like the following to send it in the format you're wanting:
let test_this = { "search": "person" };
let headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: "post" });
http.post(this.post_url, test_this, options)