I am making an app that will fetch the MySQL data using AJAX request and will post some data in the Database. It's an issue that it is not making an AJAX call in my project
I am working on Ionic 4 and PHP-MySQL as Backend service
import { Component, OnInit } from '#angular/core';
import * as $ from 'jquery';
import { data } from 'jquery';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public press() {
// tslint:disable-next-line:only-arrow-functions
$.ajax({
url: "demo_test.txt", // or any URL
success: function(result) {
$("#div1").html(result);
}});
}
}
I want to make an AJAX call from remote HTML, PHP or text file in my Ionic 4 App.
You should use httpclient from angular/http. that is very straight thing.
https://angular.io/guide/http
this.http.get(url).subscribe(data => {
console.log(data)
}, err => {
console.log(err)
}
Related
Initial Situation:
I need to implement a Google login with Ionic which works on a web platform as well as on an android device.
Therefore I use:
Ionic 5.2.2
Capacitor 1.1.1
Capacitor OAuth 2 client plugin 1.0.0
With that setup I achieved already:
Web-Login workes perfectly
Problem:
Login in from an Android device doesn't work
I followed the steps in the readme from https://github.com/moberwasserlechner/capacitor-oauth2/blob/master/README.md
I registered the plugin OAuth2Client in my app.component.ts
I implemented a method googleLogin() where I call Plugins.OAuth2Client.authenticate() with OAuth2AuthenticateOptions
app.component.ts
import { Component, OnInit } from '#angular/core';
import { registerWebPlugin } from "#capacitor/core";
import { OAuth2Client } from '#byteowls/capacitor-oauth2';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
console.log("Register custom capacitor plugins");
registerWebPlugin(OAuth2Client);
}
}
home.page.ts
import { Component } from '#angular/core';
import { Plugins } from '#capacitor/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor() { }
async googleLogin() {
try {
const resourceUrlResponse = await Plugins.OAuth2Client.authenticate({
appId: "XXX.apps.googleusercontent.com",
authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
scope: "email profile",
resourceUrl: "https://www.googleapis.com/userinfo/v2/me",
web: {
redirectUrl: "http://localhost:8100",
windowOptions: "height=600,left=0,top=0"
},
android: {
appId: "XXX.apps.googleusercontent.com",
responseType: "code",
customScheme: "com.xxx.playground.googleLogin07"
}
})
}
catch (err) {
console.error(err);
}
}
}
On an device this code results in an error-message from Google:
enter image description here
This is plausible. It seems to be that the method Plugins.OAuth2Client.authenticate() tries to do a web-based login where an android login is needed. Am I right?
If I make a call without the "web"-parameter like this...
const resourceUrlResponse = await Plugins.OAuth2Client.authenticate({
appId: "XXX.apps.googleusercontent.com",
authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
scope: "email profile",
resourceUrl: "https://www.googleapis.com/userinfo/v2/me",
android: {
appId: "XXX.apps.googleusercontent.com", //--> I tried both, android- and web-client key from the google clout platform console.
responseType: "code",
customScheme: "com.xxx.playground.googleLogin07"
}
})
...the method Plugins.OAuth2Client.authenticate() returns a blank error object --> {}
What am I doing wrong?
I am a beginner in Ionic and I am developing an app which requires a user to sign in before he places an order.
Right now, if the user tries to place an order and he is not signed in, I need a logic where I can redirect him to the login page and on success, I can redirect him back to the order page. This would have been possible in android using start activity for the result. But how can I achieve this in Ionic?
I have a solution of opening the login page using modal and dismissing it on success but I do not want to implement that solution as of now.
Here is an example whcih open modal via login. Path and IonicPage should be adjusted before using the below code. Maybe you can get a point from the code.
home.ts
import { Component } from '#angular/core';
import { AuthProvider } from '../../providers/auth/auth.provider'
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public authService:AuthProvider) {
}
goToOrder(){
this.authService.openModalViaLogin('OrderPage', {}, ()=>{})
}
}
login.ts
import { Component } from '#angular/core';
import { IonicPage, ViewController } from 'ionic-angular';
import { AuthProvider } from '../../providers/auth/auth.provider';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
constructor(public authService:AuthProvider, public viewCtrl:ViewController) {
}
login(){
this.authService.isAuthenticated = true;
this.viewCtrl.dismiss()
}
close(){
this.viewCtrl.dismiss()
}
}
auth.provider.ts
import { Injectable } from '#angular/core';
import { ModalController } from 'ionic-angular';
#Injectable()
export class AuthProvider {
public isAuthenticated:boolean = false;
constructor(public modalCtrl:ModalController) {
console.log('Hello AuthProvider Provider');
}
public openModalViaLogin(modalPage:string, params:any, callbackOnDidDismissed:Function){
if(this.isAuthenticated){
let modal = this.modalCtrl.create(modalPage,params)
modal.onDidDismiss(()=>{
callbackOnDidDismissed()
})
modal.present()
}else{
let loginModal = this.modalCtrl.create('LoginPage')
loginModal.onDidDismiss(()=>{
if(this.isAuthenticated){
let modal = this.modalCtrl.create(modalPage,params)
modal.onDidDismiss(()=>{
callbackOnDidDismissed()
})
modal.present()
}else{
console.log("failed to authenticate")
}
})
loginModal.present()
}
}
}
p.s. I think there is a more flexible way to achieve it by nav but that can be quite confusing with this short anwser.
this is my first app in nativescript and in mobile development environment in general. And I am having some difficulties. What I am trying is to make some dummy http requests with angular http module but for some reason when I debug the app inside chrome no requests seem to be made.
Here is my code:
template:
<Page>
<StackLayout>
<Button text="GET" (tap)="get()"></Button>
<Button text="POST" (tap)="post()"></Button>
</StackLayout>
</Page>
component:
import { Component } from "#angular/core";
import { AuthService } from "../../shared/auth.service";
import { HttpClient } from "#angular/common/http";
#Component({
selector: "register",
moduleId: module.id,
templateUrl: "./register.component.html"
})
export class RegisterComponent {
constructor(private auth: AuthService, private http: HttpClient) {}
get()
{
console.log('GET');
this.http.get('https://httpbin.org/get');
}
post()
{
console.log('POST');
this.http.post('https://httpbin.org/post', null);
}
}
Now when those functions execute there are no logged requests.
I am running inside an emulator and I can browse from it just fine so if someone has some ideas on what could be wrong...
You have to subscribe to the http requests else they are only defined and not called, try adding the following after this.http.get('https://httpbin.org/get') and this.http.post('https://httpbin.org/post', null):
.subscribe(
res => console.log(res),
err => console.log(err),
() => console.log("Done"),
);
Edit
I didn't mention originally, it's actually best to subscribe to the function that returns the http method, instead of subscribing to the call itself. From experience, I have found some unusual behaviour can occur
So developing this IONIC 2 app, I discoverd that sending SMS to multiple recipients isnt so trivial at it should be.
After a long research I've found this post where people trys to deal with multiple SMS. But even using their specs it doesnt work properly.
They say we can use an array of strings representing multiple phone numbers. So far so good, except it works only for the first number.
If someone has now details on this functionality I would love to hear about it.
Thanks
import { SMS } from '#ionic-native/sms';
constructor( private sms: SMS ){
this.sendSMS();
}
sendSMS() {
var MultiNumber = [ '1234567890' , '9876543210' ];
this.sms.send(MultiNumber, 'hello all this is testing message');
}
try this it is working for me, Hope it is working for you too.
So after ages of research over internet I got this litle jam called cordova-plugin-sms ( dont confuse it with cordova-sms-plugin ).
As it says in their documentation they have a function sendSMS which reeeally sends messages to multiple recipients.
So my solution for integrating it in IONIC 2 is as follows :
ionic cordova plugin add cordova-plugin-sms
and my Ionic 2 class is :
import { Component } from '#angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http, Response } from "#angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
declare let window: any;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private toastCtrl: ToastController, public navCtrl: NavController, public http: Http ) { }
ionViewDidLoad() {
this.startWhatchSMS();
}
// Android ONLY
startWhatchSMS() {
if (window.SMS) {
window.SMS.startWatch(() => {
//console.log("startWatch");
}, error => {
//console.log(error);
//console.log("error startWatch");
});
}
document.addEventListener('onSMSArrive', this.smsArived);
}
// Android ONLY
smsArived = (result: any) => {
//console.log(result);
let sms = result.data;
// put your code here...
}
sendTextMessage( ) {
window.SMS.sendSMS([ '1234567890' , '0987654321' ], 'Text message for multiple recipients',
(result) => {
console.log(result); // should be 'OK' string
}, (error) => {
console.log(error);
});
}
}
The sendTextMessage() function is called from the template by clicking an button.
Well thats it ... for me is working and hope will work for you too.
Cheers
this is my code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FileOpener } from 'ionic-native';
#Component({
selector: 'page-installHelper',
templateUrl: 'installHelper.html'
})
export class InstallHelper {
constructor(public navCtrl: NavController) {
FileOpener.open('assets/app.apk', 'application/vnd.android.package-archive').then(
function(){
console.log("success");
}, function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}
}
but I can't access the file app.apk which is in assets/app.apk
and I get the error :
Status : 9
Error : File Not Found
is it even possible to access a file within the app folders ?
Well I did it by making the app get downloaded from a server to a local folder I created in the phone and install it immediately/automatically,
Here is the code in case someone else needed it one day :
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { FileOpener } from 'ionic-native';
import { File } from 'ionic-native';
import { Transfer } from 'ionic-native';
import { HomePage } from '../pages/home/home';
declare var cordova: any;
#Component({
template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage = HomePage;
constructor(platform: Platform, public loadingCtrl: LoadingController) {
let me = this;
platform.ready().then(() => {
let loading = me.loadingCtrl.create({
content: 'Preparing The App ...'
});
loading.present();
File.createDir(cordova.file.externalDataDirectory, "appFolder", true).then(function(link){
const fileTransfer = new Transfer();
let url = 'http://yourserverhere.com/app.apk';
fileTransfer.download(url, cordova.file.externalDataDirectory +"appFolder/app.apk").then((entry) => {
loading.dismiss();
FileOpener.open(entry.toURL(), "application/vnd.android.package-archive").then(
function(){
console.log("success");
},function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}, (error) => {
console.log(error);
});
},function(error){
console.log(error);
});
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
Any explanation just ask me.
Well since you want the user to download the .apk file, you could use (in your html)
<a href="assets/app.apk" download>Download apk</a>
But the user will have to manually open his downloads (or tap the popup) to install your app.
I do not know if there is a plugin which is capable of installing these apk files. (Googling for ionic 2 install external apk didn't return any results).