how to use JSON data Coming from PHP file in Angular2? - php

export class LoginComponent
{
getdata : string;
public data;
username : any ;
password : any ;
constructor(private http: Http){}
login() {
var headers= new Headers({'Content-Type' : 'application/x-www-form-urlencoded '});
var body = JSON.stringify({
user : this.username,
pwd : this.password,
})
this.http.post('.../pos_system/Widgets/Login.php',body, {
headers:headers; })
.map(res => res.json())
.map(res => {
if(res.success)
{
this.msg="Login Complete";
}
else{
this.msg1="username and password is wrong";
}
})
.subscribe(
data =>this.getdata = JSON.stringify(data),
err => console.error(err),
() => console.log('done'));
}
}
This is my Angular2 part here i m getting JSON data from php file in res.Now I want to use this response in my angualr2 part.I want to use display username of the user which is in json data.so how to do that in angular2?

it's simple just make this change,
for Example
this.msg=res.username;
this will display username in message.
note: you need to do this in php file.
$data=array();
$df=json_decode(file_get_contents("php://input"));
$nam=$df->user;
$pws=$df->pwd;
$select=mysql_query("SELECT * FROM userData WHERE username='$nam' AND password='$pws'")or mysql_error();
$sql=mysql_num_rows($select);
if($sql>0)
{
while($row=mysql_fetch_array($select))
{
$data['success']=true;
$user=$row['username'];
$data['username']=$user;
}
}
echo json_encode($data);

Related

How can I connect my angular-nativescript app to a DB for a login?

I'm trying to create an app through NativeScript and Angular which will manage the working hours of the employees for a company.
So, I have to set up a login page and there's my problem: I linked a function on the tap of the LOGIN button and, after clicking on it, I send username and password to a service where I'm trying to connect to and end-point (mypath/api/auth.php).
In this php file I set up the DB connection and a SELECT query which receive username and password as a $_POST function. But, now, when I tap on my LOGIN button I got an alert with [Object Object] even if the credentials are right or wrong.
I'm a beginner in both NativeScript and Angular.
My PHP user verification function:
$username = $_POST["username"];
$password = $_POST["password"];
$conn = getDB();
$hash_pwd = hash('sha256', $password);
$stmt = $conn->prepare("SELECT * FROM dipendenti WHERE cod_fiscale=:username AND password=:password");
$stmt->bindParam("username", $username,PDO::PARAM_STR) ;
$stmt->bindParam("password", $hash_pwd,PDO::PARAM_STR) ;
$stmt->execute();
$count=$stmt->rowCount();
$data=$stmt->fetch(PDO::FETCH_OBJ);
closeDB($conn);
return json_encode($data);
My user.service.ts file:
import { Injectable } from "#angular/core";
import { HttpClient, HttpHeaders, HttpResponse } from "#angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError, map, tap } from "rxjs/operators";
import { Auth } from "./auth.model";
import { Config } from "../config";
#Injectable()
export class AuthService {
constructor(private http: HttpClient) { }
login( user: Auth) {
if(!user.codFiscale || !user.password) {
return throwError("Devi inserire sia codice fiscale sia la tua password per accedere");
}
return this.http.post(Config.apiUrl + 'api/auth.php',
JSON.stringify({
username: user.codFiscale,
password: user.password
}),
{
headers: this.getCommonHeaders()
}).pipe(
map(response => response),
catchError(this.handleErrors)
);
}
getCommonHeaders() {
return {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
}
handleErrors(error: Response) {
console.log(JSON.stringify(error));
return throwError(error);
}
}
My function triggered on the button tap:
submitLogin() {
if(this.isLoggingIn) {
this.authService.login(this.user).subscribe(
() => {
this.router.navigate(["/home"]);
},
(exception) => {
if(exception.error && exception.error.description) {
alert(exception.error.description);
} else {
alert(exception.error);
}
}
);
}
}
Is there something I have forgotten?
i do it in nativescript-vue, maybe you need to adjust for angular.
I use axios plugin for that, it works for ns-angular too, i just don't know how to config it on angular... but the code is this:
async submitLogin() {
const data = {
email: this.user.email,
password: this.user.password
};
try {
const res = (await api.post(this.getApiUrl+"/app/services/login.php", data)).data;
if (res.code === 200){
//handle login success
}
else if (res.code === 500){
//handle login fail
}
}
catch (e) {
console.error("Connection error: ", e);
}
},
where api.post is:
post(url, request, config) {
return axios.post(url, request, config)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error));
},
Edit: The res.code is a custom response that i send in the response, it's not default!

PHP Webhost Operation Checking

I wanted perform checking if the PHP Webhost is complete whenever perform a update function, if everything doing fine then send an notification and let the Application know the Operation is Doing fine.
Basically I wanted to know if the query in PHP work and use my application to notify the user.
is there any way or method to do so?
I using this method to fetch data from PHP in my React Native App
RecipeUpdation = () =>{
const { ID } = this.state ;
const { Name } = this.state ;
const { Type } = this.state ;
const { Ingredient } = this.state ;
const { Step } = this.state ;
return fetch('https://www.update.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
RecipeID : ID,
RecipeName : Name,
RecipeType : Type,
RecipeIngredient: Ingredient,
RecipeStep: Step
})
}).then((response) => response.json())
.then((responseJson) => {
}).catch((error) => {
console.error(error);
});
}
Basically we can verify if the Operation in PHP is successful or not by Checking the Query Execution Status. A very Basic way to do the checking is using If Else to see if the Query Function return True(Success) or False(Fail). You can also always return some Message through JsonResponds.
Here some example Code for PHP checking and Return Some Message:
// Using If Else to Check if operation Success or Not
if(mysqli_query($connection,$Your_Query)){
$MSG = 'Success' ;
// Convert message into Json format first
$json = json_encode($MSG);
// This is where it return the message to Application.
echo $json ;
}
else{
$MSG = 'Failed' ;
$json = json_encode($MSG);
echo $json ;
}
In your Application Code you already have the implementation to retrieve the JsonResponds(the Message) which have been echo in the PHP Code, I would suggest use a simple method which is Alert to pop out the message in your React Native Application to notify the User the Operation Status.
}).then((response) => response.json())
.then((responseJson) => {
// this responseJson Already have the echo Message from PHP
// just Display the Status with Alert Function
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
Hope this would help.

What value should be passed with AsyncStorage?

I am currently a beginner of react native and I want to know if I wanted to login and store user data using AsyncStorage, what key and value should be passed?
AsyncStorage.setItem('key', 'value');
UserLogin = () =>{
const { username } = this.state ;
fetch('https://www.example.com/React/user-login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('ProfileScreen', { username:username });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
If I were to say if logged in, then AsyncStorage.setItem('key', 'value');, then that could work if I want to store say the user's username so that I can display it on their profile page?
AsyncStorage parameters are both strings, so you can store serialised json data or just a plain string.
// Some code that logs someone in and gets an authentication token which then is stored
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
// then somewhere else in your code
AsyncStorage.getItem('token').then(authenticationToken => {
console.log(‘the token’, authenticationToken)
})

How to correctly handle/ get correct JSON response with PHP API and AngularJS 2 services?

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);

call rest api service from jquery

I am trying to understand restful services.i can create a class and define a function into this but when i call it through jquery it return null and when i call directly by typing url in address bar it return a json response
this is the code
class Api extends REST
{
public function processApi()
{
$func = strtolower(trim(str_replace("api/","",$_REQUEST['request'])));
if((int)method_exists($this,$func) > 0)
{
$this->$func();
}
else
{
$this->response('',404); // If the method not exist with in this class, response would be "Page not found".
}
}
private function json($data)
{
if(is_array($data))
{
return json_encode($data);
}
}
public function demo()
{
$error = array('status' => '200', "msg" => "OK");
$this->response($this->json($error), 200);
}
}
$api = new Api;
$api->processApi();
i just want to call demo method from jquery.this is what i am trying
$.post("db/api/demo",
function(data,status){
data = jQuery.parseJSON(data);
alert("Data: " + data + "\nStatus: " + status);
});
i am getting response through jquery when demo method is this
public function demo()
{
$error = array('status' => '200', "msg" => "OK");
echo json_encode($error);
//$this->response(json_encode($error), 200);
}
You should send datatype to server.
Try this code:
$.post( "db/api/demo")
.done(function( data ) {
$.each(data, function(index, element) {
alert('Data: ' + element.data + ' Status: ' + element.status);
});
}, "json");

Categories