How to delete item in Angular and PHP - php

I want to delete my item using 'srno' in my angular project. I have passed the 'srno' to the URL but it shows some error.
I checked my PHP code using postman, It is successfully worked.
I can't recognize my .ts file syntax error.
Error :
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost/angular_crud/delete.php?srno=srno", ok: false, …}
delete.component.ts
import { Component, OnInit } from '#angular/core';
import { FormControl } from '#angular/forms';
import { HttpClient, HttpParams } from '#angular/common/http';
import { ActivatedRoute } from '#angular/router';
interface Delete{
srno: String;
}
#Component({
selector: 'app-delete',
templateUrl: './delete.component.html',
styleUrls: ['./delete.component.css']
})
export class DeleteComponent implements OnInit {
delete: Delete[] = [];
srno : String;
myControl1 = new FormControl();
constructor(private http: HttpClient, public route: ActivatedRoute) { }
ngOnInit() {
}
personDelete(){
this.srno = this.myControl1.value;
var url = "http://localhost/angular_crud/delete.php?srno=srno";
this.http.get<Delete[]>(url).subscribe(data => {
this.delete = data;
console.log(data);
})
}
}
This is the delete.component.html
<h1 style="text-align: center">Adding Items here!</h1>
<div>
<p>
<mat-form-field appearance="outline" class="form_field">
<mat-label>Serial Number</mat-label>
<input [formControl]="myControl1" matInput placeholder="Enter the Serial number">
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
<mat-hint>ie : 787</mat-hint>
</mat-form-field>
</p>
</div>
<button (click)="personDelete()" mat-raised-button color="warn" class="btn">Delete</button>
This is the delete.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,DELETE');
header("Access-Control-Allow-Header: H-Requested-With");
$con = mysqli_connect("localhost","root", "", "savedata");
$srno = $_GET["srno"];
if($con->connect_error){
die("Connection failed: " . $con->connect_error);
}
$sql = "DELETE FROM savedata WHERE srno='$srno'";
if($con->query($sql) === TRUE){
echo "Record delete successfully";
}
else{
echo "Error deleting record: ". $con->error;
}
$con->close();
?>

Your API doesn't return JSON. Try
this.http
.get(url, {responseType: 'text'})
.subscribe(data => {
console.log(data);
});

Related

Cant fetch the data php back end with my login angular project

I'm trying to make an angular project but when I tried to fetch data from a php file it wont let me and there's an error such as
"Property 'success' does not exist on type 'Object'." on if(data.success){
"Property 'message' does not exist on type 'Object'." on window.alert(data.message)
here is the code
This is my loginComponent:
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private Auth: AuthService) { }
ngOnInit() {
}
loginUser(event){
event.preventDefault()
const target = event.target
const username = target.querySelector('#username').value
const password = target.querySelector('#password').value
this.Auth.getUserDetails(username, password).subscribe(data => {
if(data.success){ //this part is the error
} else {
window.alert(data.message) //this part too
}
})
}
}
this is My AuthService:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http'
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
getUserDetails(username, password){
return this.http.post('/api/auth.php', {
username,
password
})
}
}
this is my php file auth.php:
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
if(isset($_POST) && !empty($_POST)){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == 'admin' && $password == 'admin'){
?>
{
"success": true,
"secret": "This is the secret no one knows but the admin"
}
<?php
} else {
?>
{
"success": false,
"secret": "Invalid credentials"
}
<?php
}
} else {
?>
{
"success": false,
"message": "Only POST access accepted"
}
<?php
}
?>
Change your code like this in loginComponent:
this.Auth.getUserDetails(username, password).subscribe(data => {
if (data && data['success']) {
} else {
window.alert(data['message'])
}
})

angular 8 elements disappearing after post request

I'm a beginner in angular , i was trying to establish a connection with database using php as backend programming language , it was working fine and the elements were showing from database but when i inserted them to the database , it does work and they are inserted to the database but my elements disappear when the form is submitted and when the form is submitted again they flash for seconds .
MY HTML CODE
<form (submit)="loginUser($event)">
<input type="text" placeholder="User name" id="name" >
<input type="password" placeholder="password" id="pass">
<button type="submit" >Log in</button>
{{name}}
</form>
<ul *ngFor="let item of datas ">
<li>{{item.name}} {{item.pass}}</li>
</ul>
MY LOGIN.COMPONENT FILE
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { iEmployee } from '../../empolyee';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor( private Auth:AuthService) { }
public datas;
ngOnInit() {
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
loginUser(event: { preventDefault: () => void; target: any; }){
event.preventDefault();
const target = event.target;
const name=target.querySelector('#name').value;
const pass=target.querySelector('#pass').value;
this.Auth.createuser(name,pass).subscribe(data=>this.datas=data);
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
}
MY AUTH.SERVICE FILE
import { Injectable } from '#angular/core';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { iEmployee } from '../empolyee';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http:HttpClient) { }
private url : string='http://localhost:81/example/Angular/php/display.php';
private url2:string='http://localhost:81/example/Angular/php/addNew.php';
getUserDetail() {
return this.http.get(this.url)
}
createuser(name , pass) {
return this.http.post(this.url2,{name,pass},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
}
}
MY ADDNEW.PHP FILE
<?php
header('Access-Control-Allow-Origin: *');
include 'connection.php';
$data = json_decode(file_get_contents("php://input"),true);
$name= $data['name'];
$pass= $data['pass'];
$sql="insert into test(name,pass) values ('$name','$pass')";
$result = mysqli_query($con, $sql);
?>

Anuglar 6 .post .subscribe inserting record twice

I am trying to put an Angular 6 CRUD together. My addCoins method seems to be adding the record twice.
addCoin(name, price) {
const obj = {
name: name,
price: price
};
const uri = 'http://localhost/ng6crud/api/post-coins/' + name + '/' + price;
this
.http
.post(uri, obj)
.subscribe(res =>
console.log('Done'));
}
I have created a simple PHP api that sits in the ng6crud directory. The following is the code for the api/post-coins/ - If I use postman to post to the API, then it only inserts the data once.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
global $name, $price;
if(!empty($elements[3]))
{
$name = $elements[3];
}
if(!empty($elements[4]))
{
$price = $elements[4];
}
global $server;
$server = "localhost";
global $user;
$user = "someU";
global $pwd;
// $pwd = "someP"; // production
$pwd = "someP"; // local
global $db;
$db = "someDb";
//open connection to mysql db
$connection = mysqli_connect($server,$user,$pwd,$db) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "INSERT into coins (name, price) VALUES('" . $name . "','" . $price . "')";
// echo $sql;
// die();
if ($connection->query($sql) === TRUE) {
// echo "Record updated successfully";
} else {
// echo "Error updating record: " . $connection->error;
}
$connection->close();
?>
The combination of an .htaccess file and the "" tag in the httpd-vhosts.conf file allows the api/post-coins/ to accept two parameters for "name" and "price" to be included in the sql insert statement - for example api/post-coins/rupple/1.00 would insert a row into the db.
The following is the .htaccess file:
IndexIgnore * # prevent directory listing
Order deny,allow
Allow from *
# ------------------------------------------
# Rewrite so that php extentions are not shown
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php%{REQUEST_URI} [QSA,L]
The following is the Location tag within the "" tag in the httpd-vhosts.conf file:
<Location /post-coins>
ForceType appllication/x-http-php
</Location>
Once more, if I use postman to post to api/post-coins/rupple/1.00 then only one entry will be in the db. When using the service within Angular 6, it is inserting the data twice. I have tried removing the .subscribe, but then nothing is inserted and I have tried to remove the two parameters at the end of the URL, but that results is two empty entries.
Thanks in advance
To answer #Vikas question as to how I implement, the following is the create.component.html:
<div class="panel panel-primary">
<div class="panel-heading">
{{ title }}
</div>
<div class="panel-body">
<form [formGroup]="angForm" novalidate>
<div class="form-group">
<label class="col-md-4">Coin Name</label>
<input type="text" class="form-control" formControlName="name" #name />
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Coin Price</label>
<input type="text" class="form-control" formControlName="price" #price/>
</div>
<div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['price'].errors.required">
Price is required.
</div>
</div>
<div class="form-group">
<button (click)="addCoin(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</div>
The creat.component.ts:
import { Component, OnInit } from '#angular/core';
import { CoinService } from '../../service/coin.service';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
#Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
title = 'Add Coin';
angForm: FormGroup;
constructor(private coinservice: CoinService, private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
name: ['', Validators.required ],
price: ['', Validators.required ]
});
}
addCoin(name, price) {
this.coinservice.addCoin(name, price);
}
ngOnInit() {
}
}
And the coin.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class CoinService {
result: any;
constructor(private http: HttpClient) {}
addCoin(name, price) {
const obj = {
name: name,
price: price
};
const uri = 'http://localhost/ng5crud/api/post-coins/' + name + '/' + price;
this
.http
.post(uri, obj)
.subscribe(res =>
console.log('Done'));
}
getCoins() {
const uri = 'http://localhost/ng5crud/api/get-coins/';
return this
.http
.get(uri);
}
editCoin(id) {
const uri = 'http://localhost/ng5crud/api/get-coins-id/' + id;
return this
.http
.get(uri);
}
updateCoin(name, price, id) {
const uri = 'http://localhost/ng5crud/api/put-coins/' + id;
const obj = {
name: name,
price: price
};
this
.http
.post(uri, obj)
.subscribe(res => console.log('Done'));
}
deleteCoin(id) {
const uri = 'http://localhost/ng5crud/api/delete-coins/' + id;
return this
.http
.get(uri);
}
}
And the routerConfig.ts
import { Routes } from '#angular/router';
import { CreateComponent } from './components/create/create.component';
import { EditComponent } from './components/edit/edit.component';
import { IndexComponent } from './components/index/index.component';
import { DeleteComponent } from './components/delete/delete.component';
export const appRoutes: Routes = [
{ path: 'create',
component: CreateComponent
},
{
path: 'edit/:id',
component: EditComponent
},
{ path: 'index',
component: IndexComponent
},
{ path: 'delete/:id',
component: DeleteComponent
}
];
#Debojyoti, I just saw your response. I ended up creating the following, which returned nothing, but I took a look in network panel - see screen shot below:
import { HttpErrorResponse } from '#angular/common/http';
import { throwError } from 'rxjs';
import { catchError} from 'rxjs/operators';
addCoin(name, price) {
const obj = {
name: name,
price: price
};
const uri = 'http://localhost/ng5crud/api/post-coins/' + name + '/' + price;
this
.http
.post(uri, obj)
.pipe(
catchError(this.handleError) // then handle the error
)
.subscribe(res =>
console.log('Done'));
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something happened; please try again later.');
};
I figured it out and I thank each of you for helping me to step through it over and over again.
Since my PHP API is, for all intensive purposes a "GET":
const uri = 'http://localhost/ng5crud/api/post-coins/' + name + '/' + price;
Then calling a "POST" function would fire off the API twice - see attached screen shot below:
const obj = {
name: name,
price: price
};
const uri = 'http://localhost/ng5crud/api/post-coins/' + name + '/' + price;
this
.http
.post(uri, obj)
So, I changed it to a "GET" function and it works perfectly, with only one entry
addCoin(name, price) {
const obj = {
name: name,
price: price
};
const uri = 'http://localhost/ng5crud/api/post-coins/' + name + '/' + price;
this
.http
.get(uri)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
)
.subscribe(res =>
console.log('Done'));
}
Through this journey, I discovered from (another stackoverflow post - see #nodirabegimxonoyim 's answer), that map is imported differently in Angular 6 and used differently within the .get method
Instead of importing with
import 'rxjs/add/operator/map';
You use the following:
import { map } from 'rxjs/operators';
Instead of .get().map()
this
.http
.get(uri)
.map(res => {console.log(res)});
You use map, within .pipe
this
.http
.get(uri)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
)
All together, the following is my new working coin.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { HttpErrorResponse } from '#angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { map } from 'rxjs/operators';
#Injectable()
export class CoinService {
constructor(private http: HttpClient) {}
addCoin(name, price) {
const obj = {
name: name,
price: price
};
const uri = 'http://localhost/ng5crud/api/post-coins/' + name + '/' + price;
this
.http
.get(uri)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
)
.subscribe(res =>
console.log('Done'));
}
getCoins() {
const uri = 'http://localhost/ng5crud/api/get-coins/';
return this
.http
.get(uri)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
);
}
editCoin(id) {
const uri = 'http://localhost/ng5crud/api/get-coins-id/' + id;
return this
.http
.get(uri)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
);
}
updateCoin(name, price, id) {
const uri = 'http://localhost/ng5crud/api/put-coins/' + id;
const obj = {
name: name,
price: price
};
this
.http
.post(uri, id)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
)
.subscribe(res => console.log('Done'));
}
deleteCoin(id) {
const uri = 'http://localhost/ng5crud/api/delete-coins/' + id;
return this
.http
.get(uri)
.pipe(
catchError(this.handleError), // then handle the error
map(res => {
console.log(res);
})
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something happened; please try again later.');
}
}
Seriously, thank you for all your help. This takes me back to the early nineties, when programmers were nice and we would help each other.
It looks like the PHP application and Angular application are running on a separate combination of protocol (http/https), domain, and port. I see the CORS headers have been added in the PHP code.
This leads me to believe 2 requests are being made, one to see if the request is allowed according to CORS (an OPTIONS) request and the normal POST request. Hence, the record being inserted twice. You could detect the request method and return the CORS headers and set the response body to nothing as appropriate on the CORS OPTIONS request and do an insert on a POST request similar to the following (not tested).
<?php
if ($_SERVER['method'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
header("HTTP/1.1 200 OK");
exit;
}
if ($_SERVER['method'] === 'POST') {
header("HTTP/1.1 200 OK");
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
global $name, $price;
if (!empty($elements[3])) {
$name = $elements[3];
}
if (!empty($elements[4])) {
$price = $elements[4];
}
global $server;
$server = "localhost";
global $user;
$user = "someU";
global $pwd;
// $pwd = "someP"; // production
$pwd = "someP"; // local
global $db;
$db = "someDb";
//open connection to mysql db
$connection = mysqli_connect($server, $user, $pwd, $db) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "INSERT into coins (name, price) VALUES('" . $name . "','" . $price . "')";
// echo $sql;
// die();
if ($connection->query($sql) === true) {
// echo "Record updated successfully";
} else {
// echo "Error updating record: " . $connection->error;
}
$connection->close();
exit;
}
header("HTTP/1.1 404 Not Found");
exit;
?>
Make php not to accept the first pre flight request (OPTIONS)
Just modify your php code like
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
if ($_SERVER['REQUEST_METHOD'] != "OPTIONS") {
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
global $name, $price;
if (!empty($elements[3])) {
$name = $elements[3];
}
if (!empty($elements[4])) {
$price = $elements[4];
}
global $server;
$server = "localhost";
global $user;
$user = "someU";
global $pwd;
// $pwd = "someP"; // production
$pwd = "someP"; // local
global $db;
$db = "someDb";
//open connection to mysql db
$connection = mysqli_connect($server, $user, $pwd, $db) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "INSERT into coins (name, price) VALUES('" . $name . "','" . $price . "')";
// echo $sql;
// die();
if ($connection->query($sql) === TRUE) {
// echo "Record updated successfully";
} else {
// echo "Error updating record: " . $connection->error;
}
}
$connection->close();
?>

Object Object Error received when submitting form in ionic

Every time I clicked on submit button in my login page, the message it return is [Object Object]. I am trying to get users login details from the database using http request but it failed every time I run it.
I have applied to it different approach but I am still getting the same error.
I am still new to ionic and how it works, all I am doing is following some tutorials online which are not that much detailed.
My main issue is getting users details from mysql, accessing it and validate all the imputs.
Below are my Login form details:
Login.html
<ion-content class="login-content" padding>
<ion-row class="logo-row">
<ion-col></ion-col>
<ion-col >
<img src="../assets/imgs/logo.png" class="img-responsive " id="img2">
</ion-col>
<ion-col></ion-col>
</ion-row>
<div class="login-box">
<form (ngSubmit)="login()" #registerForm="ngForm">
<ion-row>
<ion-col>
<ion-list inset>
<ion-item>
<ion-input type="text" placeholder="Email" name="email" [(ngModel)]="data.email" required></ion-input>
</ion-item>
<ion-item>
<ion-input type="password" placeholder="Password" name="password" [(ngModel)]="data.password" required></ion-input>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
<ion-row>
<ion-col class="signup-col">
<div align="center">
<button ion-button class="submit-btn" full type="submit" [disabled]="!registerForm.form.valid">Login</button>
<span class="tell">- or -</span>
<button ion-button class="register-btn" type="button" block clear (click)="createAccount()">Create New Account</button>
</div>
</ion-col>
</ion-row>
</form>
</div>
</ion-content>
Login.ts
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { Myprovider } from '../../providers/myprovider/myprovider';
import { Storage } from '#ionic/storage';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
providers: [Myprovider]
})
export class LoginPage {
loading: Loading;
data: any;
public local : Storage;
constructor(private nav: NavController, private auth: Myprovider, private alertCtrl: AlertController, private loadingCtrl: LoadingController, private service: Myprovider)
{
this.data = {};
this.data.email = "";
this.data.password = "";
//this.local = new Storage();
}
ionViewDidLoad() {
this.createLoader();
}
createLoader(message: string = "Please wait...") { // Optional Parameter
this.loading = this.loadingCtrl.create({
content: message
});
}
public createAccount() {
this.nav.push('RegisterPage');
}
public login() {
this.showLoading()
let email = this.data.email;
let password = this.data.password;
let data = JSON.stringify({email, password});
this.service.login(data);
this.auth.login(this.data).subscribe(allowed => {
if (allowed) {
this.nav.setRoot('DashboardPage');
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Please wait...',
dismissOnPageChange: true
});
this.loading.present();
}
showError(text) {
this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'Fail',
subTitle: text,
buttons: ['OK']
});
//alert.present(prompt);
alert.present();
}
}
MyProvider.ts
import { HttpClient } from '#angular/common/http';
import { Http } from '#angular/http';
import { Storage } from '#ionic/storage';
import { Injectable } from '#angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
export class User {
name: string;
email: string;
}
#Injectable()
export class Myprovider {
public local : Storage;
mydata: any;
constructor(private http: HttpClient) {
this.http = http;
//this.local = new Storage()
}
currentUser: User;
public login(credentials) {
let link = "http://localhost:90/mySchool/api/securelogin.php";
return this.http.post(link, credentials)
.map(credentials => {
this.mydata = credentials;
console.log("data")
}, error =>{
console.log(error)
})
}
public register(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
// At this point store the credentials to your backend!
return Observable.create(observer => {
observer.next(true);
observer.complete();
});
}
}
public getUserInfo() : User {
return this.currentUser;
}
public logout() {
return Observable.create(observer => {
this.currentUser = null;
observer.next(true);
observer.complete();
});
}
}
Lastly, the php file
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "cihmeeting");
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
//http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$email = $request->email;
$password = $request->password;
$data = array();
if ($password != "" && $email != "") {
$sel="SELECT * FROM users WHERE email='$email' AND password='$password'";
$result=$conn->query($sel);
$numrow=$result->num_rows;
if($numrow == 1){
include 'http://localhost:90/mySchool/api/tokengenerate.php';
$token = generateRandomString();
$update = "update users set token='$token' WHERE email='$email' AND password='$password'";
$qr = $conn->query($update);
if($qr){
$st = "SELECT email, token FROM users WHERE email='$email' AND password='$password'";
$query = $conn->query($st);
while($row = $query->fetch_assoc()){
$data[] = array(
"email" => $row['email'],
"token" => $row['token']
);
echo json_encode($data);
}
}
}
}
else {
header('HTTP/1.1 401 Unauthorized', true, 401);
}
}
else {
echo "Not called properly with email parameter!";
}
?>

Angular 4 and PHP:

I've got a problem I can't seem to solve. I want to return my given input with a PHP file. This gives me the following error:
"↵Notice:
Trying to get property of non-object in
C:\xampp\htdocs\script.php on line SOMEWHERE↵null"
This is the code:
import {Component} from '#angular/core';
import {Http, Response} from '#angular/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: Http) {
}
cityName = 'From an Input field';
searchCity() {
this.http.post(
'http://localhost/directory/map/script.php', this.cityName)
.subscribe((data) => {
console.log('This is wat I get returned: ', data);
}, (error) => {
console.log('Errorrror::: ', error);
}
)
}
}
And of course my php file:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Type: application/json');
$data = json_decode(file_get_contents("php://input"));
$cityName = $data->cityName;
echo json_encode($cityName);
?>
The function searchCity() gets triggered with a button.
Replace below line:
$cityName = $data->cityName;
With this
$cityName = isset($data->cityName) ? $data->cityName : "";

Categories