AngularJs, Ionic: $http.get does not work - javascript

I am trying to load data from a mysql database with a php file and then load the result in my angularjs file. However, it is not working. I tried it with the $http service using the .get() function.
config.php:
<?php
define('HOST','localhost');
define('NAME','test');
define('USER','root');
define('PW','');
$mysqli = new mysqli(HOST,USER,PW,NAME);
if(mysqli_connect_errno())
{
//echo("Failed to connect, the error message is: ".mysqli_connect_error());
exit();
}
else
{
//echo "Connection success";
}
?>
loadDatabase.php:
<?php
require_once'config.php';
$query = "select * from lebensmittel";
$result = $mysqli->query($query);
if(mysqli_num_rows($result) > 0)
{
echo " Tupels vorhanden";
while ($row = $result->fetch_assoc())
{
$data[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($data);
?>
controller.js:
angular.module('starter.controllers', [])
.controller('AppCtrl', function ($scope, $ionicModal, $timeout, $http) {
$scope.items = [];
function loadData()
{
$http.get("http://localhost/4n/db_zugriff/loadDatabase.php").success(function (data) {
$scope.items = data;
}).error(function () {
console.log("Error: can't load from php");
});
}
loadData();
/*
$scope.items = [
{ id: 1, name: 'milk', date: '01-01-2016', amount: 1000 },
{ id: 2, name: 'cheese', date: '01-01-2016', amount: 250 },
];
*/
});
output.html:
<ion-view view-title="Output">
<ion-content data-ng-app="starter" ng-controller="AppCtrl">
<ion-list >
<ion-item ng-repeat="item in items">
{{item.name}} {{item.date}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
How can I fix this?
I appreciate your help!

Your ng-app is wrong, it should be
<ion-content data-ng-app="starter.controllers" ng-controller="AppCtrl">
Also have a function declared like this and call it in ng-init ,
$scope.loadData = function()
{
$http.get("http://localhost/4n/db_zugriff/loadDatabase.php").success(function (data) {
$scope.items = data;
}).error(function () {
console.log("Error: can't load from php");
});
});
}
HTML:
<ion-view view-title="Output">
<ion-content data-ng-app="starter.controllers" ng-controller="AppCtrl">
<ion-list ng-init="loadData()">
<ion-item ng-repeat="item in items">
{{item.name}} {{item.date}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>

Related

Click post link to display full results on another page

I want to click on a link with id from database (on posts.html page) then view the full content of that post link in a display.html using AngularJS, MySQLi, and PHP. Please see the image below:
here is what I have managed to do so far:
Posts.html
<table class="table table-bordered" ng-controller="postController"
ng-init="show_data()">
<tr>
<th>Description</th>
</tr>
<tr ng-repeat="x in news">
<td>{{x.description}}</td>
</tr>
</table>
Here is my post controller: postController.js
"USE STRICT";
app.controller('postController', function ($scope, $http) {
$scope.show_data = function () {
$http.get("display.php")
.success(function (data) {
$scope.news = data;
});
}
});
And here is my display.php code:
<?php
require_once "config.php";
$output = array();
$query = "SELECT * FROM news";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
}
?>
My display.html is:
<div >
<div>{{id}}</div>
<div>{{title}}</div>
<div>{{article}}</div>
<div>{{tag}}</div>
<div>{{author}}</div>
</div>
How to display the results fetched from the database of the particular link on display.html?
This should do the job:
In your config:
app
.config(function ($routeProvider ...) {
$routeProvider
...
.when('/posts', {templateUrl: 'posts.html', controller: function($scope, $http) {
$scope.getPosts = function() {
$http.get('posts.php').then(function (response) {
$scope.posts = response.data;
});
};
}})
.when('/display/:id', {templateUrl: 'display.html', controller: function($scope, $routeParams, $http) {
$http.get('display.php', {id: $routeParams.id}).then(function (response) {
$scope.post = response.data;
});
}})
})
In posts.html:
<table class="table table-bordered" ng-controller="postController" ng-init="getPosts()">
<tr>
<th>Description</th>
</tr>
<tr ng-repeat="post in posts">
<td><a ng-href="display/{{post.id}}">{{post.description}}</a></td>
</tr>
</table>
In display.html:
<div ng-if="post">
...
<div>{{post.title}}</div>
...
</div>
In display.php:
$id = $_GET['id'];
// then retrieve post by this id and return as json item

Fetch data using php mysql and angularJS

I using cakephp and angularJS. But I can not fetch data from controller to angularJS.
My controller:
$note2 = $this->Note->find('all', array(
'fields' => 'id, title, create_at'
));
$data_arr = array();
$i = 0;
foreach($note2 as $not){
$data_arr[$i]['id'] = $not['Note']['id'];
$data_arr[$i]['title'] = $not['Note']['title'];
$data_arr[$i]['create_at'] = $not['Note']['create_at'];
$i++;
}
echo json_encode($data_arr);
My file js:
var myApp = angular.module("myModule", []);
myApp.controller("myController", function ($scope, $http){
$http.get('/thunder_note/notes/index').then(function(result){
$scope.list_data=result;
});
});
My view:
<div ng-controller="myController">
....
<tr ng-repeat="zaa in list_data">
<td>{{zaa.id}}</td>
<td>{{zaa.title}}</td>
<td>{{zaa.create_at}}</td>
....
<div>
My json_encode($data_arr)
[{"id":"31","title":"bbbbb","create_at":"2017-10-23 13:29:37"},
{"id":"32","title":"cccc","create_at":"2017-10-23 13:29:44"}]
But when i console.log(result), follow this image:
console.log(result)
I fixed. My solution: in my controller add code: $this->autoRender=false;

Ion-refresher does not reload data properly

I'm creating an app, which loads data from JSON file. When onRefresh() function is triggered, it loads data from second JSON file instead. Everything works fine, but clicking the elements, generated from the second JSON file do not load the proper data.
So using href="#/tab/chats/{{item._id}}, before Refresh() works perfectly, but using it after, gives no results. Here are parts of the code:
<ion-view view-title="Schedule">
<ion-content ng-controller="ScheduleController">
<ion-refresher pulling-text="Pull to refresh" on-refresh="doRefresh()"></ion-refresher>
<ion-list>
<ion-item ng-repeat="item in schedule.programmeField" class="item item-thumbnail-left" href="#/tab/chats/{{item._id}}">
<img ng-src="http://###/w200/{{item._photos[0]._id}}.jpg" alt="No Image" class="padding-vertical">
<p>{{item.startField.slice(8,10) + ":" + item.startField.slice(10,12)}}</p>
<h2>{{item.titleField[0].valueField}}</h2>
<p>{{item.descField[0].valueField}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
.controller("ScheduleController", ["$scope", "$http", "$state", "$stateParams", function ($scope, $http, $state, $stateParams) {
$http.get('../downloads/bbtv.json').success(function (data) {
$scope.schedule = data;
$scope.whichelement = $stateParams.aId;
console.log($scope.whichelement);
$scope.doRefresh = function () {
$http.get('../downloads/bbtv2.json').success(function (data) {
$scope.schedule = data;
$scope.whichelement = $stateParams.aId;
$scope.$broadcast("scroll.refreshComplete");
console.log($scope.whichelement);
});
}
});
}])
.state('tab.chat-detail', {
url: '/chats/:aId',
views: {
'tab-chats': {
templateUrl: 'templates/detail.html',
controller: 'ScheduleController'
}
}
})
<ion-pane>
<ion-view>
<ion-content class="padding" ng-controller="ScheduleController">
<ion-list class="list-inset">
<ion-item class="item-text-wrap" ng-repeat="item in schedule.programmeField | filter: { _id: whichelement}">
<img ng-src="http://photos.media-press.tv/w200/{{item._photos[0]._id}}.jpg" alt="No Image" class="padding-vertical">
<h2>{{item.titleField[0].valueField}}</h2>
<p>{{item.descField[0].valueField}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
</ion-pane>

Reload ng-repeat angular / ionic

I already read some discussions about this problem but no one works for me.
I have a controller
.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
$scope.data.friends = [{username: 'test'}];
$scope.change = function(friend) {
APIUser.find(friend, function(success, data){
if (success) {
$scope.data.friends = data;
console.log($scope.data.friends);
}
})
}
}]);
I also tried
.controller('TestFriendCtrl', ['$scope', '$timeout', 'APIUser', function($scope, $timeout, APIUser) {
$scope.friends = [{username: 'coucou'}];
$scope.change = function(friend) {
APIUser.find(friend, function(success, data){
if (success) {
$timeout(function() {
$scope.friends = data;
console.log($scope.friends);
} );
}
})
console.log($scope.friends);
}
}]);
and
.controller('TestFriendCtrl', ['$scope', '$timeout', 'APIUser', function($scope, $timeout, APIUser) {
$scope.friends = [{username: 'coucou'}];
$scope.change = function(friend) {
APIUser.find(friend, function(success, data){
if (success) {
$scope.friends = angular.copy(data);
}
})
console.log($scope.friends);
}
}]);
In all cases console.log($scope.friends); return the expected value
And a view
<ion-view class="main-page">
<ion-content>
<h1>Friend</h1>
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input ng-model="friend" name="friend" type="search" placeholder="Search" ng-change="change(friend)">
</label>
{{ data.friends[0].username }}
<ion-list ng-controller="TestFriendCtrl" >
<ion-item ng-repeat="friend in data.friends" class="item-thumbnail-left">
<p>{{friend.username}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
the $scope.friend is well updated in the console output but my list does not change.
I tried to add $scope.$apply but I have $digest already in progress
You could try this, while I don't know what APIUser does:
.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
$scope.friends = [{username: 'test'}];
$scope.change = function(friend) {
APIUser.find(friend).$promise.then(function(success, data){
if (success) {
$scope.friends = data;
console.log($scope.friends);
}
}, function (err) {
console.log(err);
)};
}
}]);
Following your latest update, I assume that may have a link to the . (dot).
There is plenty of post easily foundable in google explaining why it is not goot to have a direct model without a .dot dilimiter.
Try to change your model with $scope.myDatas.friends = data; and change your ng-repeat call to ng-repeat="friend in myDatas.friends"
The comment suggesting angular.copy() was almost correct, it was just missing the second parameter. Using angular.copy() (or similarly Lodash's _.assign()) you wont lose the reference to the original array instance. See this answer or this answer for further explanation.
.controller('TestFriendCtrl', ['$scope', 'APIUser', function($scope, APIUser) {
$scope.friends = [{username: 'test'}];
$scope.change = function(friend) {
APIUser.find(friend).$promise.then(function(success, data){
if (success) {
angular.copy(data, $scope.friends);
console.log($scope.friends);
}
}, function (err) {
console.log(err);
)};
}
}]);

Fetch and display data from database in AngularJs

How can I pop the list of my clients on the screen, the list is coming from my database, I have 11 rows of clients and I want to create a listview of those and show them, this is my code:
dbFactory.method = function findAll() {
db.transaction(
function(tx) {
var sql = "SELECT (nome) as nomes FROM clientes";
log(sql);
tx.executeSql(sql, [],
function(tx, results) {
var len = results.rows.length,
clientes = [],
i = 0;
for (; i < len; i = i + 1) {
clientes[i] = results.rows.item(i).nomes;
}
log(clientes + ' found');
}
);
},txErrorHandler,
function () {
}
);
};
Controller:
.controller('ListaCtrl', function ($scope, dbFactory) {
$scope.items = dbFactory.method();
console.log(dbFactory.method());
});
clientes.html:
<ion-view view-title="Playlists" ng-app="starter">
<ion-content>
<ion-list>
<ion-item ng-repeat="itens in items" >
<p>{{itens.nome}}</p>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
The log:
Promise {$$state: Object, then: function, catch: function, finally: function}
$$state: Object
status: 1
value: SQLResultSet
insertId: [Exception: DOMException: Failed to read the 'insertId' property from 'SQLResultSet': The query didn't result in any rows being added.]
rows: SQLResultSetRowList
length: 11
__proto__: SQLResultSetRowList
rowsAffected: 0
I've managed to solve that using deferred and promise, here is what I did:
var getMessages = function findAll() {
db.transaction(
function(tx) {
var sql = "SELECT (nome) as nomes FROM clientes";
tx.executeSql(sql, [],
function(tx, results) {
var len = results.rows.length,
clientes = [],
i = 0;
for (; i < len; i = i + 1) {
clientes[i] = results.rows.item(i).nomes;
}
log(clientes + ' rowsss found');
deferred.resolve(clientes);
}
);
},txErrorHandler,
function () { }
);
return deferred.promise;
};
return {
showClientes: getMessages
};
The Controller:
.controller('ListaCtrl', function ($scope, dbFactory) {
dbFactory.showClientes().then(function(listview) {
$scope.clientes = listview;
console.log($scope.clientes);
});
});
And the html:
<ion-view view-title="Playlists" ng-app="starter">
<ion-content>
<ion-list>
<ion-item ng-repeat="cliente in clientes">
{{cliente}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Now I can see my listview with all my clients.
.controller('ListaCtrl', function ($scope, dbFactory) {
dbFactory.method().$promise.then(
function(res){
$scope.items = res; //or res.data
},
function(){
//error call back
}
);
});

Categories

Resources