Ionic: HTTP get isn't working? - ionic-framework

My HTTP get isn't loading the data and i'm not sure why. Please could someone help me? I've tried two web hosting, ones mine and i get a 'No 'Access-Control-Allow-Origin' header is present on the requested resource.' error so i used the Myjson servers and now i don't get any errors but nothing loads, please could someone help?
Here's my json file:
{
"response1": [
{
"announcement_name": "Example Message 1"
},
{
"date": "15/05/2015"
},
{
"message": "Example Message 1"
}
],
"response2": [
{
"announcement_name": "Example Message 2"
},
{
"date": "15/05/2015"
},
{
"message": "Example Message 2"
}
]
}
HTML:
<body ng-app="Announcement">
<ion-view view-title="Announcements">
<ion-pane>
<ion-header-bar class="bar-positive">
<h1 class="title">Pull To Refresh</h1>
</ion-header-bar>
<ion-view view-title="Announcements">
<ion-content ng-controller="Controller">
<ion-refresher on-refresh="doRefresh()">
</ion-refresher>
<ion-list>
<ion-item ng-repeat="item in items" ng-click="getData()">
<div class="list card">
<div class="item item-divider">{{announcement_name}} - {{date}}</div>
<div class="item item-body">
<div>
{{message}}
</div>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Javascript:
.controller('Controller', function($scope, $http) {
$scope.items = [1,2,3];
$scope.doRefresh = function() {
$http.get("https://api.myjson.com/bins/1sdnx")
.success(function(data) {
$scope.announcement_name = data.announcement_name;
$scope.date = data.date;
$scope.message = data.message;
})
.finally(function() {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
});

The actual response data, is present on the data object of the response.
.controller('Controller', function($scope, $http) {
$scope.items = [1,2,3];
$scope.doRefresh = function() {
$http.get("https://api.myjson.com/bins/1sdnx")
.success(function(result) {
console.log(result);
console.log(result.data);
$scope.announcement_name = result.data.announcement_name;
$scope.date = result.data.date;
$scope.message = result.data.message;
})
.finally(function() {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
});

Related

PayPal Checkout JS SDK - dynamically setting an amount

I'm using following js code to show paypal button on a page.
I add two radio button to select amount of payment, but I can't set it.
I save amount in variable named importoSelezionato.
But if I replace 50 with variabled,it not work.
How replace correctly number in purchaseunit with variable?
Thanks
<script>
function initPayPalButton() {
// Radiobutton IMPORTO $(document.getElementsByName('CustImporto')).on('click',function(){
var getSelectedValue = document.querySelector( 'input[name="CustImporto"]:checked');
//alert("importo selezionato: euro "+getSelectedValue.value);
var importoSelezionato = getSelectedValue.value;
});
// Radiobutton IMPORTO
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'horizontal',
label: 'pay',
},
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{"description":"Ricarica standard account","amount":{"currency_code":"EUR","value":50}}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// Show a success message within this page, e.g.
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
//aggiungere un log in una tabella di database
// Or go to another URL: actions.redirect('thank_you.html');
});
},
onError: function(err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
<div class="row">
<div class="col-lg-6 in-gp-tl">
<div class="input-group">
<span class="input-group-addon">
<input type="radio" name="CustImporto" required="" value="25" aria-label="...">
</span>
<input type="text" class="form-control" readonly="readonly" value="25" aria-label="...">
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
<div class="col-lg-6 in-gp-tb">
<div class="input-group">
<span class="input-group-addon">
<input type="radio" name="CustImporto" required="" value="50" aria-label="...">
</span>
<input type="text" class="form-control" readonly="readonly" value="50" aria-label="...">
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
Query the DOM from createOrder, which runs when a PayPal button is clicked. No need for an onclick listener...
<script>
function initPayPalButton() {
function getAmount() {
var getSelectedValue = document.querySelector( 'input[name="CustImporto"]:checked');
//alert("importo selezionato: euro "+getSelectedValue.value);
return getSelectedValue.value;
};
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'horizontal',
label: 'pay',
},
createOrder: function(data, actions) {
return actions.order.create({
"purchase_units": [
{
"amount": {
"currency_code": "EUR",
"value": getAmount()
},
"description": "Ricarica standard account"
}
]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// Show a success message within this page, e.g.
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
//aggiungere un log in una tabella di database
// Or go to another URL: actions.redirect('thank_you.html');
});
},
onError: function(err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>

Radio group not working properly when changing the radio group list values frequently in ionic 4

Ionic4 radio group misbehaving while changing the radio group list values dynamically.
Let's take my use case, I have one field country (ion-select) which has a list of countries. Another field called state (ion-radio-group) this will be visible the value based on the country selection. States will be showing fine based on the country selection but the issue is when I click the radio group it will not react in the UI. When I do doubt click the selection will be reflected in the radio group. Why it is not reflected in my first click. Please guide me.
homepage.html
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>
Home
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-item>
<ion-label>Country</ion-label>
<ion-select interface="popover" [(ngModel)]="selectedCountry['result']" (ionChange)="changeCountryCallback()">
<ion-select-option *ngFor="let country of pickListValues['country']" value="{{country.choiceValue}}"
[selected]=false>
{{country.choice}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item *ngIf="selectedCountry['result'] != ''">
<ion-row>
<ion-label>State</ion-label>
</ion-row>
<ion-row>
<ion-list lines="none">
<ion-radio-group (ionChange)="changeStateCallback()" [(ngModel)]="selectedState">
<ion-item *ngFor="let state of selectedCountry['state']">
<ion-label>{{state.choice}}</ion-label>
<ion-radio slot="start" value="{{state.choiceValue}}" [checked]="false"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
</ion-row>
</ion-item>
</ion-content>
homepage.ts
import { Component, OnInit} from '#angular/core';
#Component({
selector: 'app-homepage',
templateUrl: './homepage.html',
styleUrls: ['./homepage.scss'],
})
export class homepage implements OnInit {
private pickListValues = {
country: [{
choiceValue: "in",
choice: "India",
child: {
value: [{
choiceValue: "tn",
choice: "Tamilnadu",
child: {
value: []
}
}, {
choiceValue: "dl",
choice: "Delhi",
child: {
value: []
}
}, {
choiceValue: "mi",
choice: "Mumbai",
child: {
value: []
}
}]
}
}, {
choiceValue: "ci",
choice: "China",
child: {
value: [{
choiceValue: "AH",
choice: "Anhui Province",
child: {
value: []
}
}, {
choiceValue: "GX",
choice: "Guangxi Zhuang",
child: {
value: []
}
}]
}
}, {
choiceValue: "jp",
choice: "Japan",
child: {
value: [{
choiceValue: "gu",
choice: "Gunma",
child: {
value: []
}
}, {
choiceValue: "kw",
choice: "Kanagawa",
child: {
value: []
}
}, {
choiceValue: "oki",
choice: "Okinawa",
child: {
value: []
}
}, {
choiceValue: "tok",
choice: "Tokushima",
child: {
value: []
}
}]
}
}]
}
selectedCountry = {
result: "",
state: []
}
selectedState: any;
constructor() {
}
ngOnInit() {
}
changeCountryCallback() {
console.log("Country Value : ", this.selectedCountry['result']);
this.pickListValues['country'].forEach(element => {
console.log("Element : ", element);
if (element['choiceValue'] == this.selectedCountry['result']) {
this.selectedCountry['state'] = [];
this.selectedCountry['state'] = element['child']['value'];
}
})
}
changeStateCallback() {
console.log("State Value : ", this.selectedState);
}
}
My expected behavior is the radio group to be working fine with a single click after changing the country values frequently
Please watch up to end of the video you can understand my issue. Click here for video
<ion-content>
<ion-item>
<ion-label>Country</ion-label>
<ion-select interface="popover" [(ngModel)]="selectedCountry['result']" (ionChange)="changeCountryCallback()">
<ion-select-option *ngFor="let country of pickListValues['country']" value="{{country.choiceValue}}" [selected]=false>
{{country.choice}}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item *ngIf="selectedCountry['result'] != ''">
<ion-row>
<ion-label>State</ion-label>
</ion-row>
<ion-row>
<ion-list lines="none">
<ion-radio-group (ionChange)="changeStateCallback()" [(ngModel)]="selectedState">
<ion-item *ngFor="let state of selectedCountry['state']">
<ion-label>{{state.choice}}</ion-label>
<ion-radio slot="start" value="{{state.choiceValue}}" [checked]="selectedState==state.choiceValue"></ion-radio>
</ion-item>
</ion-radio-group>
</ion-list>
</ion-row>
</ion-item>
</ion-content>
You can accomplish by the above mentioned way([checked]="selectedState==state.choiceValue"). Here I checked which one is selected from the passed array. So on the first click, it should be working fine. Please try it and share the feedback.
<div>
<ion-label class="heading">Gender</ion-label>
<div *ngFor='let gend of gen'>\\ gen have my details
<ion-radio-group [(ngModel)]="register.Gender" [ngModelOptions]="{standalone: true}">
<ion-row style='margin-top:10px'>
<ion-col size='10'>
<ion-label style='color: #b4b4b4;margin:0 0 0 40px'> {{gend.name}}</ion-label>
</ion-col>
<ion-col size='2'>
<ion-radio [value]="gend.name"></ion-radio>\\value bind to ngModel
</ion-col>
</ion-row>
</ion-radio-group>
</div>
</div>

Magento2: How to show .phtml file in a popup

I need to open the data from a .phtml file (gallery.phtml) in a modal popup in Magento2. This is the code used to include modal scripts:
<div>
Click Me
</div>
<script>
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
content: 'gallery.phtml',
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function () {
this.closeModal();
}
}]
};
var popup = modal(options, $('#popup-mpdal'));
$("#click-me").on('click',function(){
$("#popup-mpdal").modal("openModal");
});
}
);
</script>
The gallery.phtml file is given below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="popup-mpdal">
<h1> Hi I'm here.... </h1>
</div>
</body>
</html>
But the popup is not coming.
I got the answer:
<div>
Click Me
</div>
<div id="popup-mpdal" >
<?php include ($block->getTemplateFile('Vendor_Module::gallery.phtml')) ?>
</div>
<script>
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function () {
this.closeModal();
}
}]
};
var popup = modal(options, $('#popup-mpdal'));
$("#click-me").on('click',function(){
$("#popup-mpdal").modal("openModal");
});
}
);
</script>
I have used this in html
<button type="button" class="action" data-trigger="trigger">
<span data-bind="i18n: 'Click Here'"></span>
</button>
<div data-bind="mageInit: {
'Magento_Ui/js/modal/modal':{
'type': 'popup',
'title': 'Popup title',
'trigger': '[data-trigger=trigger]',
'responsive': true,
'buttons': [{
text: 'Submit',
class: 'action'
}]
}}">
<div class="content">
Popup Content
</div>
</div>

Ionic views without navigation

I am building my first hybrid app with Ionic, and there is something I do not understand.
What is the use of ion-nav-view.
I explain: I have an app with "nav-tabs". Here is the code of a nav-tab:
<ion-tab title="Contacts" icon="icon-users" href="#/tab/contacts">
<ion-nav-view name="tab-contacts"></ion-nav-view>
</ion-tab>
Everything is OK here.
So now, my list of contacts is a list which goes like this:
<ion-item href="#/tab/contacts/{{contact.id}}" ng-repeat="contact in contacts | orderBy:'name'">
{{contact.name}}
</ion-item>
Here is my problem: I have configured a route for '/tab/contacts/:id', and a view. The problem is: where should I put the equivalent of the "ion-nav-view" directive, so that my view is actually shown when I click?
Thank you!
I think the best answer is a working example similar to what you want to do.
However <ion-nav-view> must be in your index.html and it is where the route/state manager will put the templates of your views. The templates have another directive, <ion-view>, which wraps all other directives and content of the view.
Check the snippet below:
angular.module('ionicApp', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tabs', {
url: '/tab',
abstract: true,
templateUrl: 'views/tabs.html'
})
.state('tabs.contacts', {
url: '/contacts',
views: {
'tab-contacts': {
templateUrl: 'views/contacts.html',
controller: 'contactsCtrl',
resolve: {
allcontacts: function(Contacts) {
console.log("resolve allcontacts");
return Contacts.all();
}
}
}
}
})
.state('tabs.detail', {
url: '/detail/:id',
views: {
'tab-detail': {
templateUrl: 'views/detail.html',
controller: 'detailCtrl',
resolve: {
contact: function($stateParams, Contacts) {
return Contacts.get($stateParams.id);
}
}
}
}
});
$urlRouterProvider.otherwise("/tab/contacts");
})
.controller('contactsCtrl', function($scope, $ionicLoading, $ionicPopover, $ionicPopup, $compile, $http, allcontacts) {
console.log("contactsCtrl");
$scope.contacts = allcontacts;
})
.controller('detailCtrl', function($scope, contact, $ionicHistory) {
$scope.contact = contact;
console.log("detailCtrl", contact);
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
})
.factory('Gravatar', function() {
return {
getUrl: function(s){
return "https://secure.gravatar.com/avatar/"+CryptoJS.MD5(""+Math.random())+"?d=identicon&s="+s;
}
}
})
.factory('Contacts', function($http, $q, $timeout, Gravatar) {
var contacts = [];
return {
all: function(){
var dfd = $q.defer();
//$http.get('../data/contacts.json').then(function(response){
$timeout(function() {
//contacts = response.data;
contacts = [{
id: 1,
name: "William",
surname: "Hayes",
fullname: "Grace Beatty",
image: Gravatar.getUrl(128)
}, {
id: 2,
name: "James",
surname: "Jennings",
fullname: "Hilda Gross",
image: Gravatar.getUrl(128)
}, {
id: 3,
name: "Judith",
surname: "Silverman",
fullname: "Bruce Kern",
image: Gravatar.getUrl(128)
}, {
id: 4,
name: "Greg",
surname: "Fitzpatrick",
fullname: "Heather Bowers",
image: Gravatar.getUrl(128)
}, {
id: 5,
name: "Teresa",
surname: "McLean",
fullname: "Leon Baker",
image: Gravatar.getUrl(128)
}, {
id: 6,
name: "Emily",
surname: "Lassiter",
fullname: "Virginia Pittman",
image: Gravatar.getUrl(128)
}, {
id: 7,
name: "Don",
surname: "Sinclair",
fullname: "Ashley Richards",
image: Gravatar.getUrl(128)
}, {
id: 8,
name: "Hazel",
surname: "Livingston",
fullname: "Gloria O",
image: Gravatar.getUrl(128)
}, {
id: 9,
name: "Regina",
surname: "Braun",
fullname: "Monica Casey",
image: Gravatar.getUrl(128)
}, {
id: 10,
name: "Leroy",
surname: "Pritchard",
fullname: "Gretchen Sharpe",
image: Gravatar.getUrl(128)
}];
//console.log(contacts);
dfd.resolve(contacts);
console.log("contacts.all");
});
return dfd.promise;
},
get: function(id) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].id == id) {
return contacts[i];
}
}
return null;
}
}
});
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic detail view</title>
<link href="http://code.ionicframework.com/nightly/css/ionic.min.css" rel="stylesheet">
<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
</head>
<body>
<ion-nav-bar class="bar-positive">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
<script id="views/tabs.html" type="text/ng-template">
<ion-tabs class="tabs-icon-top tabs-color-active-positive">
<ion-tab title="Contacts" icon-off="ion-ios-people-outline" icon-on="ion-ios-people" href="#/tab/contacts">
<ion-nav-view name="tab-contacts"></ion-nav-view>
</ion-tab>
<ion-tab title="Contact detail" icon-off="ion-ios-person-outline" icon-on="ion-ios-person href="#/tab/detail">
<ion-nav-view name="tab-detail"></ion-nav-view>
</ion-tab>
</ion-tabs>
</script>
<script id="views/contacts.html" type="text/ng-template">
<ion-view title="Contacts">
<ion-content>
<ion-list>
<ion-item class="item item-thumbnail-left" ng-repeat="contact in contacts" ui-sref="tabs.detail({ id: contact.id })">
<img ng-src="{{ contact.image }}" />
<h2>{{ contact.name }}</h2>
<p>{{ contact.fullname }}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
</script>
<script id="views/detail.html" type="text/ng-template">
<ion-view title="Contact detail">
<ion-nav-buttons side="left">
<button class="button button-clear" ng-click="myGoBack()" >
<i class="icon ion-ios-arrow-back"></i>
Back</button>
</ion-nav-buttons>
<ion-content>
<ion-item class="list-item">
<img ng-src="{{ contact.image }}" alt="{{ contact.name }}" />
<div class="list-details">
<p class="sub-heading"><b>Name:</b> {{ contact.name }}</p>
<p><b>Surname:</b> {{ contact.surname }}</p>
<p><b>Fullname:</b> {{ contact.fullname }}</p>
</div>
</ion-item>
</ion-content>
</ion-view>
</script>
</body>
</html>

collections2 and meteor-cfs-autoform to upload and display image

I am using collections2 and meteor-cfs-autoform for schemas and to upload and display image using cfs:gridfs storage adaptor package but unable to show images in template.Can you please tell me where i am doing mistake and its solution.
collections.js
Recipes = new Mongo.Collection('recipes');
Reviews = new Mongo.Collection('reviews');
RecipesImages = new FS.Collection("recipesImages", {
stores: [new FS.Store.GridFS("recipesImages")]
});
RecipesImages.allow({
insert: function(userId, doc) {
return true;
},
update: function(userId, doc, fieldNames, modifier) {
return true;
},
download: function(userId) {
return true;
},
fetch: null
});
Recipes.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Recipe Name",
max: 100
},
ingredients: {
type: [Object],
minCount: 1
},
"ingredients.$.name": {
type: String
},
"ingredients.$.amount": {
type: String
},
description: {
type: String,
label: "How to prepare ",
},
time: {
type: Number,
label: "Time (Minutes)",
},
image: {
type: String,
autoform: {
afFieldInput: {
type: "cfs-file",
collection: 'recipesImages',
label: 'Recipe Picture'
}
}
}
}));
recipes.js
Template.recipes.helpers({
'showRecipes':function(){
return Recipes.find();
},
'images': function () {
return RecipesImages.findOne({_id:id}) ;
}
})
recipes.html
<template name="recipes">
{{#each showRecipes}}
<div class=" col-md-4">
<div class="panel panel-default mb " >
<div class="panel-image">
<img src="{{this.url }}" class="panel-image-preview" />
</div>
<div class="panel-body">
<h4>{{name}}</h4>
<p>{{description}}</p>
</div>
<div class="panel-footer text-center" >
<p>its footer </p>
</div>
</div>
</div>
{{/each}}
</template>
Are you importing cfs:ui? If not, you should include it so that you can use the FS.GetFile helper. Then you can use this code.
Recipes Template
<template name="recipes">
{{#each showRecipes}}
<div class=" col-md-4">
<div class="panel panel-default mb " >
<div class="panel-image">
{{#with FS.GetFile "recipesImages" image}}
<img src="{{url}}" class="panel-image-preview" />
{{/with}}
</div>
<div class="panel-body">
<h4>{{name}}</h4>
<p>{{description}}</p>
</div>
<div class="panel-footer text-center" >
<span class="glyphicon glyphicon-open-file"></span>
</span><small> {{time}}</small>
<span class="glyphicon glyphicon-heart likes" style="vertical-align:middle"></span><small>2 </small>
<span class="glyphicon glyphicon-share"></span>
</div>
</div>
</div>
{{/each}}
</template>
Recipes helpers
Template.recipes.helpers({
'showRecipes':function(){
return Recipes.find();
}
});
Here's the link to cfs:ui documentation