Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) - php

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

Related

push notifications do NOT shown to the subscribers (web-push-php)

I'm using web-push-php library for my project. The user can register/un-register for web notification but the message does NOT push to the specific user. following are my codes
main.js
'use strict';
const applicationServerPublicKey = ew.vars.PubKey;
const pushButton = document.querySelector('.pushBTN');
let isSubscribed = false;
let swRegistration = null;
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
//CODE HERE
//1
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
})
.catch(function(error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
//2
function initializeUI() {
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
//3
function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}
if (isSubscribed) {
pushButton.innerHTML = '<i class="fas fa-bell-slash text-danger"></i>';
} else {
pushButton.innerHTML = '<i class="fas fa-bell text-success"></i>';
}
pushButton.disabled = false;
}
//4
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
initializeUI();
})
//5
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
}
//6
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
//7
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
//8
function updateSubscriptionOnServer(subscription) {
// TODO: Send subscription to application server
if (subscription) {
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('webpushregister.php', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))) : null,
axn: 'subscribe'
})
}).then(function(response) {
return response.text();
}).then(function(response) {
console.log(response);
}).catch(function(err) {
// Error :(
console.log('error');
});
} else {
//subscriptionDetails.classList.add('is-invisible');
}
}
//9
function unsubscribeUser() {
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
//updating database
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('webpushregister.php', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))) : null,
axn: 'unsubscribe'
})
}).then(function(response) {
return response.text();
}).then(function(response) {
console.log(response);
}).catch(function(err) {
// Error :(
console.log('error removing from db');
throw new error('error removing from db');
});
//end updating database
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
}
//10
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
// TODO: Tell application server to delete subscription
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
my sw.js
'use strict';
//1
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Codelab';
const options = {
body: 'Yay it works.4444444444',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
const notificationPromise = self.registration.showNotification(title, options);
event.waitUntil(notificationPromise);
});
//2
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
});
//installing web application
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
console.log("Installing web app");
return caches.open("offline").then(function(cache) {
console.log("caching index and important routes");
return cache.addAll(["/", "/offline.html"]);
});
};
self.addEventListener("fetch", function(event) {
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match("offline.html");
} else {
return matching;
}
});
});
};
and my php file
<?php
$siteconf = new SiteConfig();
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
$subscriber = ExecuteRow("SELECT * FROM subscribers ORDER BY id DESC LIMIT 1");
$auth = array(
'VAPID' => array(
'subject' => 'https://github.com/Minishlink/web-push-php-example/',
'publicKey' => $siteconf->PublicKey, // don't forget that your public key also lives in app.js
'privateKey' => $siteconf->PrivateKey, // in the real world, this would be in a secret file
),
);
// array of notifications
$notifications = [
[
'subscription' => Subscription::create([
'endpoint' => $subscriber['endpoint'],
'publicKey' => $siteconf->PublicKey,
'authToken' => $subscriber['auth'],
]),
'payload' => 'hello !',
],
];
$webPush = new WebPush($auth);
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
/**
* Check sent results
* #var MessageSentReport $report
*/
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}
/**
* send one notification and flush directly
* #var \Generator<MessageSentReport> $sent
*/
$sent = $webPush->sendNotification(
$notifications[0]['subscription'],
$notifications[0]['payload'], // optional (defaults null)
true // optional (defaults false)
);
?>
I'm trying to send message to the last user in our database. I receive success message but the push message does NOT deliver.
What's the reason? how to fix it?
You are missing the following:
'contentEncoding' => $message["contentEncoding"]
It should be placed under the comment // array of notifications.
I am having an issue regarding this but it's the opposite of yours. I am only able to send a notification for the very last row but not the other rows.

Timeout alert displayed with no log errors

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

why am i getting this incorrect entry pop up but my php file executes login successfully

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

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!";
}
?>

Ionic image upload with PHP server

I have a problem with my ionic app.
I want to upload an image to my php server when i click on a button but it seems that i am doing something wrong...
Communication.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic3 Server Send Test
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<button ion-button (click)="uploadFile()">Upload</button>
</ion-item>
</ion-list>
</ion-content>
Communication.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '#angular/common/http';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '#ionic-native/file-transfer';
#Component({
selector: 'communication',
templateUrl: 'communication.html'
})
export class CommunicationPage {
imageURI:any;
imageFileName:any;
constructor(public navCtrl: NavController,
private transfer: FileTransfer) {}
uploadFile() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'ionicfile',
fileName: 'ionicfile',
chunkedMode: false,
headers: {}
}
fileTransfer.upload('C:/Users/Nathan/Desktop/Recognize/src/pages/communication/test.png', 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
}
}
I have this error when i click on the upload button :
FileTransferError {code: 1, source:"C:/Users/Nathan/Desktop/Recognize/src/pages/communication/test.png", target: "http://someserver", http_status: null, body: null, …}
I know there is a problem with the url of the "test.png" file because of code 1 error.
Do you have any idea ?
You need to add image targetPath in fileTransfer.upload() like this,
var targetPath = this.file.dataDirectory + imgName;
fileTransfer.upload(targetPath, 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
Hey Nathan the problem you are having is because of the URL of file, here you are giving the url only test.png.
Rather than you should use FileChooser plugin for cordova which gives the absolute URL of the file.
import { FileChooser } from '#ionic-native/file-chooser';
constructor(private fileChooser: FileChooser) { }
function() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'ionicfile',
fileName: 'ionicfile',
chunkedMode: false,
headers: {}
}
this.fileChooser.open()
.then(uri => {
fileTransfer.upload(uri, 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
})
.catch(e => console.log(e));
}
Comment down if you want some more help.

Categories