I tried to do a login & register page. After click on the register button, timeout alert error shown but there are no log errors. Although the timeout alert is shown,the data I used to register is successfully saved in MYSQL database
register.page.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { ToastController, LoadingController, AlertController } from '#ionic/angular';
import { AccessProviders } from '../providers/access-providers';
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
u_name : string = "";
u_email_address : string = "";
u_password : string = "";
u_confirm_password : string = "";
disabledButton;
constructor(
private router : Router,
private toastCtrl : ToastController,
private loadingCtrl : LoadingController,
private alertCtrl : AlertController,
private accsPrvds: AccessProviders
) { }
ngOnInit() {
}
ionViewDidEnter(){
this.disabledButton = false;
}
async tryRegister(){
if(this.u_name == ""){
this.presentToast('Name is required');
}else if(this.u_email_address == ""){
this.presentToast('Email is required');
}else if(this.u_password == ""){
this.presentToast('Password is required');
}else if(this.u_confirm_password != this.u_password){
this.presentToast('Password are not the same');
}else{
this.disabledButton = true;
const loader = await this.loadingCtrl.create({
message: 'Please wait a moment...',
});
loader.present();
return new Promise(resolve =>{
let body = {
aksi: 'proses_register',
u_name: this.u_name,
u_email_address: this.u_email_address,
u_password: this.u_password
}
this.accsPrvds.postData(body, 'proses_api.php').subscribe((res:any)=>{
if(res.success==true){
loader.dismiss();
this.disabledButton = false;
this.presentToast(res.msg);
this.router.navigate(['/login']);
}else{
loader.dismiss();
this.disabledButton = false;
this.presentToast(res.msg);
}
},(err)=>{
loader.dismiss();
this.disabledButton = false;
this.presentAlert('Timeout');
});
});
}
}
async presentToast(a){
const toast = await this.toastCtrl.create({
message : a,
duration: 1500,
position: 'top'
});
toast.present();
}
async presentAlert(a){
const alert = await this.alertCtrl.create({
header: a,
backdropDismiss: false,
buttons: [
{
text: 'Close',
handler: (blah) => {
console.log('Confirm Cancel: blah');
//action
}
}, {
text: 'Try Again',
handler: () => {
this.tryRegister();
}
}
]
});
await alert.present();
}
}
login.page.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { ToastController, LoadingController, AlertController, NavController } from '#ionic/angular';
import { AccessProviders } from '../providers/access-providers';
import { Storage } from '#ionic/storage';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
u_email_address : string = "";
u_password : string = "";
disabledButton;
constructor(
private router : Router,
private toastCtrl : ToastController,
private loadingCtrl : LoadingController,
private alertCtrl : AlertController,
private accsPrvds: AccessProviders,
private storage : Storage,
public navCtrl : NavController
) { }
ngOnInit() {
}
ionViewDidEnter(){
this.disabledButton = false;
}
async tryLogin(){
if(this.u_email_address == ""){
this.presentToast('Email is required');
}else if(this.u_password == ""){
this.presentToast('Password is required');
}else{
this.disabledButton = true;
const loader = await this.loadingCtrl.create({
message: 'Please wait a moment...',
});
loader.present();
return new Promise(resolve =>{
let body = {
aksi: 'proses_login',
u_email_address: this.u_email_address,
u_password: this.u_password
}
this.accsPrvds.postData(body, 'proses_api.php').subscribe((res:any)=>{
if(res.success==true){
loader.dismiss();
this.disabledButton = false;
this.presentToast('Login successful');
this.storage.set('storage_xxx', res.result); // create storage session
this.navCtrl.navigateRoot(['/home']);
}else{
loader.dismiss();
this.disabledButton = false;
this.presentToast('Email or password is incorrect');
}
},(err)=>{
loader.dismiss();
this.disabledButton = false;
this.presentToast('Timeout');
});
});
}
}
async presentToast(a){
const toast = await this.toastCtrl.create({
message : a,
duration: 1500
});
toast.present();
}
openRegister(){
this.router.navigate(['/register']);
}
}
proses_api.php
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE,OPTIONS");
header("Access-Control-Allow-Headers: Origin, Content-Type, Authorization, Accept, X-Requested-With, x-xsrf-token");
header("Content-Type: application/json; charset=UTF-8");
include "config.php";
$postjson = json_decode(file_get_contents('php://input'), true);
$today = date('Y-m-d H:i:s');
if($postjson['aksi']=="proses_register"){
$checkemail = mysqli_fetch_array(mysqli_query($mysqli,
"SELECT u_email_address FROM user_info WHERE u_email_address='$postjson[u_email_address]'"));
if ($checkemail['u_email_address']==$postjson['u_email_address']){
$result = json_encode(array('success'=>false, 'msg'=>'Email address is already registered'));
}else{
$password = md5($postjson['password']);
$insert = mysqli_query($mysqli, "INSERT INTO user_info SET
u_name = '$postjson[u_name]',
u_email_address = '$postjson[u_email_address]',
u_password = '$password',
u_createdon = '$today'
");
if($insert){
$result = json_encode(array('success'=>true, 'msg'=>'Register successful'));
}else{
$result = json_encode(array('success'=>false, 'msg'=>'Register failed'));
}
}
echo $result;
}
else if($postjson['aksi']=="proses_login")
{
$password = md5($postjson['password']);
$logindata = mysqli_fetch_array(mysqli_query($mysqli,
"SELECT * FROM user_info WHERE u_email_address='$postjson[u_email_address]' AND u_password='$u_password"));
$data = array(
'u_id' => $logindata['u_id'],
'u_name' => $logindata['u_name'],
'u_email_address' => $logindata['u_email_address'],
);
if($logindata){
$result = json_encode(array('success'=>true, 'result'=>$data));
}else{
$result = json_encode(array('success'=>false));
}
echo $result;
}
?>
I can't really find errors in this code, anyone know how solve this or find anything I have missed.
Thank you
you can put the following line in register.page.ts to show the error.
console.log(err);
Related
Why am i getting this incorrect entry pop up but my php file executes login successfully. its confusing where file should i edit is it the ts file or the php file i need some eyes and brains to fix this code I've provided i need you guys. I hope you guys takes time to help everyone especially those who don't have much knowledge of ionic3 as this framework don't have much resources to learn it deeply thankyou for your future answers.
login.html
<ion-list style="padding: 50px">
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input name="username" #username></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Password</ion-label>
<ion-input type="password" name="userpass" #userpass></ion-input>
</ion-item>
<div style="padding-top: 50px ">
<button ion-button block (click)="signIn()">Sign In</button>
<button ion-button outline block (click)="RegisterPage()">Register</button>
</div>
</ion-list>
login.ts
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { Http, Headers, RequestOptions } from "#angular/http";
import { LoadingController } from 'ionic-angular';
import 'rxjs/add/operator/map';
import { RegisterPage } from '../register/register';
import { TabsPage } from '../tabs/tabs';
import { HomePage } from '../home/home';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
#ViewChild("username") username;
#ViewChild("userpass") userpass;
data: string;
items: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public alertCtrl: AlertController,
private http: Http,
public loading: LoadingController
)
{
}
RegisterPage() {
this.navCtrl.push(RegisterPage)
}
signIn() {
//// check to confirm the username and userpass fields are filled
if (this.username.value == "") {
let alert = this.alertCtrl.create({
title: "ATTENTION",
subTitle: "Username field is empty",
buttons: ['OK']
});
alert.present();
} else
if (this.userpass.value == "") {
let alert = this.alertCtrl.create({
title: "ATTENTION",
subTitle: "Password field is empty",
buttons: ['OK']
});
alert.present();
} else {
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({
headers: headers
});
let data = {
username: this.username.value,
userpass: this.userpass.value
};
let loader = this.loading.create({
content: 'Processing please wait...',
});
loader.present().then(() => {
this.http.post('http://localhost/8990API/login.php', data, options)
.map(res => res.json())
.subscribe(res => {
console.log(res)
loader.dismiss()
if (res.status == "Login successfully") {
let alert = this.alertCtrl.create({
title: "CONGRATS",
subTitle: (res.message),
buttons: ['OK']
});
alert.present();
this.navCtrl.push(HomePage, data);
this.navCtrl.push(TabsPage);
}
else {
let alert = this.alertCtrl.create({
title: "Incorrect entry please try again.",
subTitle: (res.message),
buttons: ['OK']
});
alert.present();
}
});
});
}
}
}
login.php
<?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);
}
require "dbconnect.php";
$data = file_get_contents('php://input');
if (isset($data)) {
$request = json_decode($data,true);
if (!empty($request) && isset($request['username'], $request['userpass'])) {
$username = $request['username'] ?? '';
$userpass = $request['userpass'] ?? '';
$userpass = sha1($userpass."#la]#}^(dy*%-Ga=/,Ga!.");
$sql = "SELECT * FROM useraccount WHERE username = '$username' and userpass = '$userpass'";
$result = mysqli_query($con, $sql);
if ($result && ($count = mysqli_num_rows($result)) > 0) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// $active = $row['active'];
$status = "success";
$message = "Login successfully";
}
else {
$status = "fail";
$message = "Your Login Username or Password is invalid";
}
}
else {
$status = "fail";
$message = "You must specify a Username and Password";
}
}
else {
$status = "fail";
$message = "You must specify a Username and Password";
}
echo json_encode(array('status' => $status, 'message' => $message, 'data' => $data));
?>
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'])
}
})
The form has text input and file-input. I studied the tutorial from here.
This is my add.component.ts file:-
import { AdminPage } from '../../../_models/admin.page.model';
import { AdminPageService } from '../../../_admin_service/admin.page';
import { ImageUploadService } from '../../../_common_service/image.upload';
export class AddComponent implements OnInit, AfterViewInit {
.............
.............
adminPageModel = new AdminPage('', '', '', '','');
constructor(private route: ActivatedRoute,
private router: Router,
private _adminPage: AdminPageService,
private _imageUpload: ImageUploadService,
fb: FormBuilder,
private _flashMessagesService: FlashMessagesService) {
this.addPageFormGroup = fb.group({
'title' : [null, Validators.compose([Validators.required])],
'meta_keyword': [null, Validators.required],
'meta_description': [null, Validators.required],
'image':[],
'desc': [null, Validators.required]
});
}
formImageUpload(event){
this._imageUpload.onFileChange(event,this.addPageFormGroup);
}
submitAddPage(value:any){
this.addPageFormGroup.get('desc').setValue($('.Editor-editor').html());
const adminPageModule = this._imageUpload.prepareSave(this.addPageFormGroup);
this._adminPage.postAdminPageAdd(adminPageModule).subscribe(
data => {
this.responseStatus = data;
if(this.responseStatus.status == 1)
{
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 2000 });
}
else
{
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-danger', timeout: 2000 });
}
},
err => {
console.log(err)
},
() => {}
);
this.status = true;
}
}
This is the image.upload.ts service file, where we are setting the formdata from the form:-
#Injectable()
export class ImageUploadService {
constructor() {}
onFileChange(event, formHasImage:any) {
if(event.target.files.length > 0) {
let file = event.target.files[0];
formHasImage.get('image').setValue(file);
}
}
prepareSave(formHasImage): any {
let input = new FormData();
input.append('image', formHasImage.get('image').value);
input.append('title', formHasImage.get('title').value);
input.append('desc', formHasImage.get('desc').value);
input.append('meta_keyword', formHasImage.get('meta_keyword').value);
input.append('meta_description', formHasImage.get('meta_description').value);
console.log(input);
return input;
}
}
This is the admin.page.ts service file where we are hitting the API. This is made by referring to this answer here.
#Injectable()
export class AdminPageService {
http : Http;
actionUrl : string;
admin_page_add_url: string;
postAdminPageAddData: AdminPage;
adminPageAddResponse:Object= [];
constructor(public _http: Http) {
this.http = _http;
this.admin_page_add_url = 'http://localhost/angproject/phpscript/adminpage2.php';
}
// The form Data is being sent as parameter
postAdminPageAdd(postAdminPageAddFormData: any) {
let headers = new Headers();
headers.append('enctype', 'multipart/form-data');
headers.append('Accept', 'application/json');
this.actionUrl = this.admin_page_add_url;
return this.http.post(this.actionUrl,
{ postAdminPageAddFormData },
{ headers: headers })
.map(res => res.json()).share();
}
}
This is the server side php file where we are sending the data. This is made on the accepted answer here:-
<?php
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers: Content-Type, enctype");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header('Content-Type: application/json; charset=utf-8');
header('enctype: multipart/form-data');
include('connection.php');
$error = array();
if(isset($_FILES['image']))
{
$image = 'Image Exists';
}
else
{
$error[] = "Image was not entered";
$image = '';
}
if(isset($_POST['title']) && !empty($_POST['title']))
$title = $_POST['title'];
else
$error[] = "Title was not entered";
if(empty($error))
{
$response['status'] = 1;
$response['message'] = $image;
$response['error'] = $conn->error;
}
else
{
$response['status'] = 0;
$response['message'] = "Parameter missing";
$response['error'] = $error;
}
$respond = json_encode($response);
echo $respond;
exit;
?>
My issue is, I am always getting this json response:-
{
"status": 0,
"message": "Parameter missing",
"error": [
"Image was not entered",
"Title was not entered"
]
}
It seems like the formdata aren't being sent to the server end. What am I doing wrong here? Mind it, I have other process too, to submit the form. But in that case, I can send data to server successfully by not using formdata and hence, I can't implement file-upload in that method.
Note: When I do console.log(input), I get this:-
You have two problems with your AdminPageService's postAdminPageAdd method.
First, Headers.append() does not mutate the Headers object, it returns a new Headers object with the original headers and the new one. So you need to do something like:
let headers = new Headers();
headers = headers.append('enctype', 'multipart/form-data');
headers = headers.append('Accept', 'application/json');
Second, the FormData object in the post should not be surrounded with curly brackets - it should work if you do:
return this.http.post(
this.actionUrl,
postAdminPageAddFormData,
{ headers: headers }
).map(res => res.json()).share();
Try appending file directly to FormData object.
#Injectable()
export class ImageUploadService {
file: File;
constructor() {}
onFileChange(event, formHasImage:any) {
if(event.target.files.length > 0) {
file = event.target.files[0];
}
}
prepareSave(formHasImage): any {
let input = new FormData();
input.append('image', this.file);
input.append('title', formHasImage.get('title').value);
input.append('desc', formHasImage.get('desc').value);
input.append('meta_keyword', formHasImage.get('meta_keyword').value);
input.append('meta_description', formHasImage.get('meta_description').value);
console.log(input);
return input;
}
}
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!";
}
?>
I know this topic already exist on this platform. I have searched through online but I didn't get the rightful answer pertaining to my problem.
I created a login page which needs to access API but every time I clicked on the Login button the error comes out.
I have tried different ways but still couldn't figure it out.
Below is my source codes:
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>
<form (submit)="doLogin()">
<ion-item>
<ion-input [(ngModel)]="credentials.email" name="email" type="text" placeholder="Email Address" ></ion-input>
</ion-item>
<ion-item>
<ion-input [(ngModel)]="credentials.password" name="password" type="password" placeholder="Password"></ion-input>
</ion-item>
<button ion-button class="submit-btn" block type="submit">
Login
</button>
</form>
<button ion-button class="register-btn" block clear (click)="register()">
Create New Account
</button>
</ion-content>
AuthServive.ts
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = 'http://localhost:90/mySchool/api2/get.php?';
#Injectable()
export class AuthService {
constructor(public http: Http) {}
login(credentials) {
let urlDest = "http://localhost:90/mySchool/api2/get.php?username=" + credentials.email + "&password=" + credentials.password;
return this.http.get(urlDest)
.map( (res:Response) => res.json());
/* return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'login', JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});*/
}
register(data) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'guest/signup', JSON.stringify(data), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
logout(){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('X-Auth-Token', localStorage.getItem('token'));
this.http.post(apiUrl+'logout', {}, {headers: headers})
.subscribe(res => {
localStorage.clear();
}, (err) => {
reject(err);
});
});
}
}
Login.ts
import { Component } from '#angular/core';
import { NavController, LoadingController, ToastController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { TabsPage } from '../tabs/tabs';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';
export class User {
email: string;
password: string;
}
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
credentials: User = {
email: '',
password: ''
}
items:any;
loading: any;
//loginData = { email:'', password:'' };
//data: any;
constructor(public navCtrl: NavController, public authService: AuthService, public loadingCtrl: LoadingController, private toastCtrl: ToastController) {}
doLogin() {
//this.showLoader();
this.authService.login(this.credentials)
.subscribe(
datas => {
//this.loading.dismiss();
if(datas.result){
this.navCtrl.push(HomePage, {
email: datas.data.id
})
}else{
alert("Invalid user or password")
}
});
/*this.authService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
localStorage.setItem('token', this.data.access_token);
this.navCtrl.setRoot(TabsPage);
}, (err) => {
this.loading.dismiss();
this.presentToast(err);
});*/
}
register() {
this.navCtrl.push(RegisterPage);
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Processing...'
});
this.loading.present();
}
presentToast(msg) {
let toast = this.toastCtrl.create({
message: msg,
duration: 3000,
position: 'bottom',
dismissOnPageChange: true
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
}
get.php
<?php
header('Access-Control-Allow-Origin: *');
// Set up the PDO parameters
$Mysqli = new mysqli('127.0.0.1', 'root', '', 'cihmeeting');
$login = addslashes($_GET['email']);
$Tsenha = addslashes($_GET['password']);
//$senha= md5($Tsenha);
$erro = "";
$erro .= empty($login) ? "Enter your email \n" : "";
$erro .= empty($senha) ? "Enter your password \n" : "";
$arr = array();
if(empty($erro)){
$query = "SELECT * FROM users WHERE email = '$login' and password = '$Tsenha'";
$result = $Mysqli->query($query);
if($result->num_rows > 0){
//login Logged
$obj = $result->fetch_object();
$arr['result'] = true;
$arr['data']['id'] = $obj->id;
$arr['data']['zone_code'] = $obj->zone_code;
$arr['data']['first_name'] = $obj->first_name;
$arr['data']['email'] = $obj->email;
}else{
$arr['result'] = false;
$arr['msg'] = "Invalid login details";
}
}else{
$arr['result'] = false;
$arr['msg'] = $erro;
}
echo json_encode($arr);
?>
Could someone please point me to the right direction.
It's because your API doesn't return valid JSON response. You should catch these errors:
login(credentials) {
let urlDest = "http://localhost:90/mySchool/api2/get.php?username=" + credentials.email + "&password=" + credentials.password;
return this.http.get(urlDest)
.map( (res:Response) => res.json())
.catch(error => {
// handle error here
console.log('Server error');
});
}