I am developing one PWA of the ionic capacitor and there is a requirement to load another website in an iframe so from one of the ionic app component I called another site.
iframe.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="end" (click)="goBack()">
Close
<ion-icon slot="icon-only" name="close-outline"></ion-icon>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<iframe #iframe height="100%" width="100%" title="test"></iframe>
</ion-content>
iframe.page.ts
export class IframePage implements OnInit, AfterViewInit {
userId = localStorage.getItem('userId');
gameData: any;
gameUrl: any;
docId;
#ViewChild('iframe') iframe: ElementRef;
constructor(private navCtrl: NavController,
private authSrv: AuthService,
private commanSrv: CommannService,
private router:Router) {
firebase.analytics().logEvent('Web_game');
this.iframe.nativeElement.setAttribute('src', 'anotherdomain.com?UID=sadsajdhsakjhdasjhkjsd');
window.addEventListener('message', (event) => {
console.log(event.data);
if (event.data.res === 'win') {
// let routename = commanSrv.getLastRoute();
// navCtrl.navigateForward(routename || 'home_tab');
this.router.navigate(['arcade-outcome', { type: 'arcade_win' }]);
} else if (event.data.res === 'loss'){
this.router.navigate(['arcade-outcome', { type: 'arcade_lose' }]);
} else {
// if (event.data === 'closed') {
let routename = commanSrv.getLastRoute();
navCtrl.navigateBack(routename || 'home_tab');
// }
}
});
}
}
And now
another site is made up of HTML and javascript and here is code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="assets/icon/favicon.png" />
<link rel="stylesheet" type="text/css" href="./assets/css/custom.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-database.js"></script>
<script src="scripts/firebase.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
<title>HTML 5 game application</title>
</head>
<body>
<p>Loader screen</p>
<div class="loader"></div>
<script>
$(document).ready(function(){
const serverUrl = 'https://us-central1-domain.cloudfunctions.net/';
var token;
var xhttp = new XMLHttpRequest();
var gamePlayData;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userId = urlParams.get('UID')
const gamePlay = urlParams.get('gameplay')
const mode = urlParams.get('mode')
function getUserDetails(token) {
console.log("getUserDetails start token ", token);
console.log(firebase);
firebase.auth().signInWithCustomToken(token).then((userCredential) => { // execution stop from here.
console.log("getUserDetails end");
var user = userCredential.user;
if (user !== null) {
window.location.replace(`anotherdomain.com/start.html?id=${userId}&gamePlay=${gamePlay}`);
}
})
.catch((error) => {
console.log('error in catch: ', error);
var errorCode = error.code;
var errorMessage = error.message;
// window.history.back();
alert('User is not logged in.')
// parent.postMessage('closed', '*');
});
}
function checkAuth() {
console.log("ajax call start");
$.ajax({
type: "POST",
url: serverUrl + 'checkAuthStatus',
data: { uid: userId },
success: function (response) {
console.log("ajax call end");
//if request if made successfully then the response represent the data
getUserDetails(response.result);
},
error: function (err) {
console.log(err);
}
});
}
checkAuth();
});
</script>
From the line
firebase.auth().signInWithCustomToken(token).then(() => {
Execution cancelled and iframe got closed , window.addEventListener('message', (event) => { got called navigated to ionic application back.
The surprising is, this issue only occurs in iPhone whereas for android it is working fine.
When navigating to another domain site 3rd time then it working and got the success in firebase.auth().signInWithCustomToken(token).then((userCredential) => { .
Please help me.
Related
i'm using Codeigniter 3.11, php 7.4, and jquery 3.5.1. Recently, i create a rest API using restserver in Codeigniter. And this rest server will be hosted once finished. Below is the code for controller in the server:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
require 'vendor/autoload.php';
use chriskacerguis\RestServer\RestController;
class Genre extends RestController
{
private const PATH_MODEL = 'Genre_model';
private const PARAM_CATEGORY = 'c';
private const PARAM_LIMIT = 'l';
private const PARAM_GROUPED = 'g';
private const PARAM_STATUS = 'status';
private const PARAM_MESSAGE = 'messages';
private const PARAM_RESULT = 'result';
private const STATUS_OK = 'ok';
private const STATUS_ERROR = 'error';
public function __construct()
{
parent::__construct();
$this->load->model($this::PATH_MODEL, 'genre');
}
public function index_get()
{
$limit = (isset($_GET[$this::PARAM_LIMIT])) ? (int) $_GET[$this::PARAM_LIMIT] : 0;
$isGrouped = (isset($_GET[$this::PARAM_GROUPED])) ? (int)($_GET[$this::PARAM_GROUPED]) : false;
$this->response(
array(
$this::PARAM_STATUS => $this::STATUS_OK,
$this::PARAM_MESSAGE => 'success get data.',
$this::PARAM_RESULT => $this->genre->getGenre($limit, $isGrouped)
),
RestController::HTTP_OK
);
}
}
?>
And this is the code for client:
$("#btn").on("click", function() {
var settings = {
"url": "localhost/local-api/v1/genre?g=1&l=5",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
"method": "GET",
"timeout": 0,
};
$.ajax(settings).done(function(response) {
console.log(response);
});
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">Click me</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
</html>
I'm getting this error when i want to request to localhost using jquery ajax.
jquery-3.5.1.min.js:2 GET http://localhost/local-api/localhost/local-api/v1/genre?g=1&l=5 404 (Not Found)
Can anyone explain why the link get duplicated? and how to solve it? thank you for your interest.
Just getting the hang of API calls and fetch and have put together the below code to fetch some info from the Trip Advisor API and log a message to the console using this info.
When I call the fetch request function it logs to the console just fine, but as soon as I wrap it in an event listener callback it no longer executes, why is this?
Appreciate any help!
//This is the fetch function kept in a file names request.js
const findRest = async (reviews, closed) => {
const respond = await fetch(
"https://tripadvisor1.p.rapidapi.com/restaurants/list-by-latlng?limit=30¤cy=EUR&distance=2&lunit=km&lang=en_US&latitude=53.3498&longitude=-6.2603",
{
method: "GET",
headers: {
"x-rapidapi-host": "tripadvisor1.p.rapidapi.com",
"x-rapidapi-key": /* my rapidapi key */
}
}
);
if (respond.status === 200) {
let data = await respond.json();
let newData = await data.data;
let data1 = await newData.filter(
review => parseInt(review.num_reviews) >= reviews
);
let data2 = await data1.filter(close => close.is_closed == closed);
return data2;
} else {
throw new Error("Could not provide results within specified parameters");
}
};
//This is the event listener kept in a file names app.js - both files are active and no problems communicating with each other
document.querySelector(".subButton").addEventListener("click", e => {
e.preventDefault();
console.log("click");
const userReviews = parseInt(document.querySelector(".userRev").value);
const userClose = document.querySelector(".userClose").value;
findRest(userReviews, userClose)
.then(data => {
data.forEach(element => {
console.log(
`${element.name} matches your search criterea and is located at ${element.address}
To make a booking, please call ${element.phone}`
);
});
})
.catch(err => {
console.log(err);
});
});
//HTML below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>What Wine?</title>
<meta name="author" content="Phil My Glass" />
<meta
name="description"
content="An app to help you find the wine you like or something new based on your preferences"
/>
<meta name="keywords" content="wine" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<header>
<h1>What Restaurant?</h1>
</header>
<main>
<form>
<input class="userRev" /><br />
<input class="userClose" />
<button class="subButton" type="submit">Find!</button>
</form>
</main>
</body>
<script src="req.js" type="text/Javascript"></script>
<script src="app.js" type="text/Javascript"></script>
</html>
Those two lines look like they could break the thread:
const userReviews = parseInt(document.querySelector(".userRev").value);
const userClose = document.querySelector(".userClose").value;
If either one of document.querySelector(".userRev"), document.querySelector(".userClose") is null, that will be uncaught TypeError.
Will know for sure with the HTML.
I'm doing my homework for a JS course and I face a strange problem. I've made a request 'module' that I'm at the very beginning right after jquery then I'm loading the essential js scripts but when I try to use a function from the request module in another script file it always throws a TypeError undefined. The strange is that when I console.log the object it is' not undefined and everything is all right. I can't seem to figure it out why this is happening ... and I need some guideline
Here is part of the code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SeenIt</title>
<link rel="stylesheet" href="style/site.css">
<link rel="stylesheet" href="style/post.css">
<link rel="stylesheet" href="style/header.css">
<link rel="stylesheet" href="style/menu.css">
<link rel="stylesheet" href="style/notifications.css">
<link rel="stylesheet" href="style/submit.css">
<link rel="stylesheet" href="style/comments.css">
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="./scripts/request.js"></script>
<script src="../node_modules/handlebars/dist/handlebars.min.js"></script>
<script src="./scripts/pageView.js"></script>
<script src="./scripts/app.js"></script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
My JS Request Module
let request = (function (){
const appKey = 'kid_rkR4UTRnb';
const appSecret = 'd3e9f15502a740fcb1413d7ffe109ab5';
const baseUrl = 'https://baas.kinvey.com';
function createAuth(type)
{
let authorize = {"Content-Type": "application/json"};
if(type === 'basic')
{
authorize.Authorization = "Basic " + btoa(appKey + ':' + appSecret);
}
else if(type === 'kinvey')
{
authorize.Authorization = "Kinvey " + localStorage.getItem('authtoken');
}
return authorize;
}
function makeRequest(destination, endpoint, method, authorization, data)
{
let req = {
url: baseUrl + '/' + destination + '/' + endpoint,
method: method,
headers: createAuth(authorization),
};
if(data != undefined) req.data = JSON.stringify(data);
$.ajax(req);
}
function register(username, password)
{
let data = {
"username": username,
"password": password
};
return makeRequest('user', appKey, 'POST', 'basic', data);
}
function logIn(username, password)
{
let data = {
"username": username,
"password": password
};
return makeRequest('user', appKey + '/login', 'POST', 'basic', data);
}
function logout()
{
makeRequest('user', appKey + '/_logout', 'POST', 'kinvey');
}
return {
createAuth,
register,
logIn,
logout
}
})();
Main JS App file
$(() => {
let main = $('#container');
initialState();
$(document).ajaxStart(() => $('#loadingBox').show());
$(document).ajaxComplete(() => $('#loadingBox').hide());
$('#infoBox').click(() => $('#infoBox').hide());
$('#errorBox').click(() => $('#errorBox').hide());
$(document).on('submit', '#loginForm', login);
async function viewPage(page)
{
if(page == 'home')
{
main.html(await loadWelcome(isLoggedIn()));
}
}
// initial functions
function initialState()
{
viewPage('home');
}
///////////////
// session control
function login(e)
{
e.preventDefault();
let loginForm = $(this);
let name = loginForm.find('input[name="username"]').val();
let password = loginForm.find('input[name="password"]').val();
request.logIn(name, password) // TYPEERROR UNDEFINED ?!?
.then(data => {
request.saveSession(data);
this.reset();
viewPage('home');
})
}
});
It crashes when you try to invoke the then() method because the request.logIn() function returns undefined instead of a promise. This can be traced to the makeRequest() function which doesn't return anything, i.e. undefined.
Your last line in the makeRequest() function needs to be:
return $.ajax(req);
Please try return object on JS Request Module like this,
return {
createAuth: createAuth,
register: register,
logIn: logIn,
logout: logout
}
You can try <script> attributes for the correct loading scripts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SeenIt</title>
<link rel="stylesheet" href="style/site.css">
<link rel="stylesheet" href="style/post.css">
<link rel="stylesheet" href="style/header.css">
<link rel="stylesheet" href="style/menu.css">
<link rel="stylesheet" href="style/notifications.css">
<link rel="stylesheet" href="style/submit.css">
<link rel="stylesheet" href="style/comments.css">
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
<script src="../node_modules/handlebars/dist/handlebars.min.js"></script>
<script defer src="./scripts/request.js"></script>
<script defer src="./scripts/pageView.js"></script>
<script defer src="./scripts/app.js"></script>
</head>
<body>
<div id="container">
</div>
</body>
</html>
in your code, function makeRequest doesn't return any value, so it will return undefined. try returning the value from the makeRequest function.
I want show elastic search data on web page that using angular js.
however, not bring data from elasticsearch with that message
Is there anything I need to add or fix in my code?
if anyone answers to me I really appreciate
I have attached an execution screen.
thank you.
Execution screen:
enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController"></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'http://localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
"match_all" : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
}).catch(function (err) {
if (err.status === 404) {
alert("error 404" );
} else {
alert("error : " + err );
}
});
});
</script>
</body>
</html>
I am using AngularJS, HTML 5, JavaScript and Rest API to upload an image in database.
The back-end is made on Hibernate and it is working perfectly.
The image is being converted to base64 String and then it is being send to Rest API.
The problem is that the image is being uploaded in the database but there is an error showing in the console.
Here is he code
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.min.js"></script>
<script type="text/javascript"
src="https://cdn.rawgit.com/adonespitogo/angular-base64-upload/master/src/angular-base64-upload.js"></script>
</head>
<body ng-app="pic" ng-controller="MainController">
<input type="file" ng-model="image" base-sixty-four-input>
<button ng-click="upload()">Upload</button>
<div ng-bind="message"></div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Main JS File
URI = "http://localhost:8085/PictureUpload/api/";
var app = angular.module('pic', [ 'naif.base64' ])
app.controller("MainController", [ '$scope', '$http', function($scope, $http) {
$scope.image = {};
$scope.upload = function() {
try {
var data = angular.toJson($scope.image.base64);
console.log(data)
var responsePromise = $http.post(URI + "PictureAPI",data);
} catch (err) {
$scope.message = "There is some system Issue, Please contact Administrator";
}
responsePromise.success(function(dataFromServer,
status, headers, config) {
$scope.message=dataFromServer;
console.log($scope.message)
});
responsePromise.error(function(data, status, headers,
config) {
});
}
} ])
API File
package com.pic.API;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.tomcat.util.codec.binary.Base64;
import com.google.gson.Gson;
import com.pic.DAO.PictureDAO;
import com.pic.resources.AppConfig;
#Path("/PictureAPI")
public class PictureAPI {
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response saveImage(String dataRecieved) {
System.out.println(dataRecieved);
Gson gson = new Gson();
Response returnValue = null;
byte[] image = Base64.decodeBase64(dataRecieved);
System.out.println(image);
PictureDAO pd = new PictureDAO();
try {
pd.savePicture(image);
String value = "Photo Uploaded";
returnValue = Response.ok(value).build();
} catch (Exception e) {
String message = AppConfig.PROPERTIES.getProperty(e.getMessage());
String value = gson.toJson(message);
if (e.getMessage().contains("DAO")) {
returnValue = Response.status(Status.SERVICE_UNAVAILABLE)
.entity(value).build();
} else {
returnValue = Response.status(Status.BAD_REQUEST).entity(value)
.build();
}
}
return returnValue;
}
}
Error in Console.
angular.js:13642 SyntaxError: Unexpected token P in JSON at position 0
at wc (angular.js:1352)
at dc (angular.js:10455)
at angular.js:10546
at q (angular.js:322)
at gd (angular.js:10545)
at c (angular.js:11343)
at angular.js:16104
at m.$eval (angular.js:17378)
at m.$digest (angular.js:17191)
at m.$apply (angular.js:17486)