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);
?>
Related
So i'm building a QRcode scanner app.
When I scan a barcode, I want another modal to appear but I want to data (decoded from barcode) to be passed to my child Component which is ResponseModal.
here is my code
QrScanner.js
import { useHistory } from "react-router-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";
import React, { useEffect, useState} from "react";
import axios from 'axios';
import ResponseModal from './ResponseModal';
const QrScanner = () => {
const [data, setData ] = useState('');
const [flag, setFlag] = useState(false);
const history = useHistory();
useEffect(() => {
if(data === '') {
return;
}
if (Number.isInteger(parseInt(data))) { // barcode scanned
axios.get('/some/endpoint/code/' + data)
.then(res => {
if (res.data != false) {
setFlag(true);
} else{
setData('Sorry, Wrong barcode!');
}
})
}
})
return (
<>
<BarcodeScannerComponent
width={500}
height={500}
onUpdate={(err, result) => {
if (result) {
setData(result.text);
}
}}
/>
<p className="modal-result-show">{data}</p> <---- this updates fine when barcode is scanned
<ResponseModal open={flag} data={data}/> <---- this is empty, why?
</>
);
}
export default QrScanner
And here is my ResponseModal:
import 'react-responsive-modal/styles.css';
import Modal from 'react-responsive-modal';
import React, {useEffect, useState} from "react";
const ResponseModal = (flag, data) => {
const [open, setOpen] = useState(false);
const onCloseModal = () => setOpen(false);
console.log(data); <----- empty
useEffect(() => {
if(flag.open === true) {
setOpen(true);
flag.open = false;
}
})
return (
<>
<Modal open={open} onClose={onCloseModal}>
<div className="qr-modal-header-stock">
<h5>Enter fulfillment stock</h5>
<form action="/some/another/endpoint/save" method="POST">
<input type="hidden" name="ean" value={data} /> <--- empty
<input type="number" name="product_stock" class="form-control"/> <br />
<input type="submit" class="btn btn-primary form-control"/>
</form>
</div>
</Modal>
</ >
);
}
export default ResponseModal
My question is, why am I not receing the data in my ResponseModal? I thought whenever {data} updates, everything that uses it also re-renders or being passed. What am I missing? I need {data} to do some logic with it on my backend side.
You are using props wrong way. props is one object, just update like this.
const ResponseModal = (props) => {
const {flag, data} = props;
}
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);
});
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!";
}
?>
Hello i have a problem returning data on html file using an Ionic app. I use an auth-service.ts provider to connect to database and the results are returning fine on console-> network-> XHR (friendsNewsFeed)
On ionic serve i am getting error
trying to diff [object Object] only arrays and iterables are allowed
https://forum.ionicframework.com/t/problem-with-ngfor/121590
home.ts
import { Component, ViewChild } from "#angular/core";
import { NavController, App, AlertController } from "ionic-angular";
import { AuthService } from "../../providers/auth-service";
import { Common } from "../../providers/common";
import { Camera, CameraOptions } from "#ionic-native/camera";
#Component({ selector: "page-home", templateUrl: "home.html" })
export class HomePage {
public photos: any;
public base64Image: string;
public fileImage: string;
public userDetails: any;
public resposeData: any;
public dataSet: any;
public noRecords: boolean;
userPostData = {
uid: "",
token: "",
created: "",
message: ""
};
constructor(
public authService: AuthService
) {
const data = JSON.parse(localStorage.getItem("userData"));
this.userDetails = data.userData;
this.userPostData.uid = this.userDetails.uid;
this.userPostData.token = this.userDetails.token;
this.userPostData.created = "";
this.noRecords = false
this.getFeed();
}
ngOnInit() {
this.dataSet = [];
}
getFeed() {
this.common.presentLoading();
this.authService.postData(this.userPostData, "userNewsFeed").then(
result => {
this.resposeData = result;
if (this.resposeData) {
this.common.closeLoading();
this.dataSet = this.resposeData;
console.log(this.dataSet);
} else {
console.log("No access");
}
},
err => {
//Connection failed message
}
);
}
home.html
<ion-card *ngFor="let item of dataSet; let msgIndex = index">
<ion-item>
<ion-card-content>
<p [innerHTML]="item.message | linky"></p>
</ion-card-content>
</ion-item>
</ion-card>
auth-service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";
//let apiUrl = 'https://api.thewallscript.com/restful/';
/*
Generated class for the AuthService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class AuthService {
constructor(public http: Http) {
console.log('Hello AuthService Provider');
}
postData(credentials, type){
return new Promise((resolve, reject) =>{
let headers = new Headers();
this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
subscribe(res =>{
resolve(res.json());
}, (err) =>{
reject(err);
});
});
}
}
any hint?
I am able to fetch the value I add in my textbox in a variable in my addoperation.ts file, but I am unable to send it to my database.
Here is my addoperation.ts code:
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Headers, Http, HttpModule ,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-operationadd',
templateUrl: './operationadd.component.html',
styleUrls: ['./operationadd.component.css']
})
export class OperationaddComponent implements OnInit {
name="abc";
constructor(private http: Http) { }
ngOnInit() {
}
submitdata(){
console.log("Data Submitted");
console.log(this.name);
this.http.post('http://example.com/adv8/prod-api/crudtable-add.php', {name: this.name})
.map((res:Response) => res.json())
.subscribe(result =>{ });
}
}
and this is my addoperation.html
<form>
<div class="form-group">
<label for="name">First Name:</label>
<input type="text" class="form-control" #fname [(ngModel)]="name" name="firstname">
</div>
<button type="submit" class="btn btn-default" (click)="submitdata()">Submit</button>
</form>
My API is working fine, I have tested it on Chrome Postman. I pass a variable name: jess in the body and I get a SUCCESS message, but I am unable to save it from Angular.
After a lot of search i am able to post the data in my db, below I am pasting code , should be useful to someone in future.
Note: adding headers is important.
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Headers, Http, HttpModule ,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-operationadd',
templateUrl: './operationadd.component.html',
styleUrls: ['./operationadd.component.css']
})
export class OperationaddComponent implements OnInit {
name="abc";
constructor(private http: Http) { }
ngOnInit() {
}
submitdata(){
console.log("Data Submitted");
console.log(this.name);
var body = "name=" + this.name;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://example.com/adv8/prod-api/crudtable-add.php', body, {
headers: headers
})
.map(res => res.json())
.subscribe(
// data => this.saveJwt(data.id_token),
// err => this.logError(err),
() => console.log('Authentication Complete')
);
}
}