Fetch data using php mysql and angularJS - javascript

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;

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

ngTagsInput with filtered auto-complete

I am trying to create a tags input-field, with auto-complete. Here is the Angular code:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get(Routing.generate('my_route_to_json_data'));
}
});
HTML code:
<body ng-app="plunker" ng-controller="MainCtrl">
<tags-input ng-model="tags" add-on-paste="true" display-property="categoryname" placeholder="Add a Tag">
<auto-complete max-results-to-show="4" min-length="0" source="loadTags($query)"></auto-complete>
</tags-input>
<p>Model: {{tags}}</p>
</body>
The $http.get(Routing.generate('my_route_to_json_data')); returns tags.json :
[{"categoryname":"wifi"},{"categoryname":"cable"},{"categoryname":"tv"},{"categoryname":"geyser"},{"categoryname":"fridge"},{"categoryname":"sofa"},{"categoryname":"lift"},{"categoryname":"gas stove"},{"categoryname":"washing machine"}]
This works perfeclty. When I enter some input in the field, the suggestions appear in the dropdown.
Problem: Now I want the suggestions being displayed to be filtered, based on user input.
For that I changed my Angular code to this:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, tags) {
$scope.loadTags = function(query) {
return tags.load();
};
});
app.service('tags', function($q, $http, $filter) {
var tags = $http.get(Routing.generate('my_route_to_json_data'));
this.load = function(query) {
var deferred = $q.defer();
deferred.resolve( $filter('filter')($scope.tags, query));
return deferred.promise;
};
});
Doesn't work :(
Any and all help is appreciated.
Here is the console:
I would change the service to something like:
app.service('tags', function($q, $http, $filter) {
this.load = function(query) {
return $http.get(Routing.generate('my_route_to_json_data')).then(
function(result) {
return $filter('filter')(result.data, query)
}
)
};
});
The service now return a chained promises and the resolve function is dealing with the filter.
You can cache the results, and return a promise (Using the $q service) that relove the array of tags previously returned from the server.
Don't know if the filter itself is working - But now it will have list of items to filter and not undefined value ($scope.tags).

Increment the Mongoose query limit by button click/scroll in AngularJS

I want to increment the data via Button click or scroll.
I have a function which loads the data after button click loadDataQueryDB(param, param, param). With that, I am passing data to MongoDB query.
Well how can I increment my var limit = 50; + 5; after each button click?
Node.js
router.get('/load', function(req, res) {
var skip = 0;
var limit = 50;
var place_val = req.query.place;
var category_val = req.query.category;
var specCategory_val = req.query.specCategory;
if(category_val, specCategory_val, place_val){
Experiences
.find({category : category_val, city:place_val})
.lean()
.skip(skip)
.limit(limit)
.exec(function(err, docs_accommo) {
res.send(docs_accommo);
console.log("First");
});
}
});
Angular.js
app.controller('loadData', ['$scope', '$http', '$window', '$upload', '$rootScope',
function($scope, $http, $window, $upload, $rootScope) {
$scope.loadDataQueryDB = function(place_value, category_value, specCategory_value){
console.log(place_value);
console.log(category_value);
console.log(specCategory_value);
$scope.datafront = [];
var options = {
place : place_value,
category: category_value,
specCategory : specCategory_value
};
$http.get('/load',
{params: options})
.success(function(data) {
$scope.datafront = data;
});
};
});
HTML
<div ng-click="loadDataQueryDB(place, category, specCategory)">
<div ng-repeat="x in datafront | limitTo:? track by x._id" ng-cloak>
{{x}}
</div>
</div>
<button class="btn btn-default" style="float:right; margin-bottom:20px;"/>
Something like the code below, using services and http promises, the data returned form the server its on promise.data.
app.controller('loadData', ['$scope', '$http', '$window', '$upload', '$rootScope','dataService',
function($scope, $http, $window, $upload, $rootScope, dataService) {
$scope.loadDataQueryDB = function(place_value, category_value, specCategory_value){
console.log(place_value);
console.log(category_value);
console.log(specCategory_value);
$scope.datafront = [];
var params = {
place : place_value,
category: category_value,
specCategory : specCategory_value
skip : $scope.skip,
limit : $scope.limit
}
dataService.getData(params).then(function(promise){
$scope.dataFront = promise.data;
//Increment the limit by ten
$scope.limit =+ 10;
})
};
});
app.module('dataService').factory('dataService',['$http',function ($http) {
var service = {};
factory.getData= function (params) {
var promise = $http({
method: 'GET',
url: '/load',
params: params
});
return promise;
}
return service;
}]);
You should have only the gets that return views on the router and the rest of the get and post calls on a service, at least I develop like that and its more confortable.

search and repeat cities with ng-repeat and openweathermap api

Hi guys I've been trying for a while now to sort data braught from openweathermap.org using the api provided by the site and the ng-repeat feature in angularjs. for some reason i can't seem to get it to work... what I'm trying to do is to first display all of the gathered data and then sort it using the input field.
Javascript
var app = angular.module('weatherApp', []);
app.controller('weatherController', function($scope, $http) {
$http.jsonp('http://api.openweathermap.org/data/2.5/weather', { params : {
q : $scope.city,
units : $scope.units,
callback: 'JSON_CALLBACK',
APPID: $scope.id
}}).success(function(data){
$scope.data = data;
});
$scope.units = 'metric';
$scope.id = 'e08f9689f06c1b6eddb44396c749eb54';
$scope.reset = function(){
return $scope.city = "";
};
});
HTML
<div ng-app="weatherApp" ng-controller="weatherController">
<input ng-model="city.name" placeholder="City" />
<button ng-click="reset()">Reset</button>
<ul>
<li ng-repeat=" x in data | filter : city">
{{x.name}}
</li>
</ul>
You could try to set the $scope.id and $scope.units before calling $http.jsonp. Seems to me that the values are used in the parameters before being set. Try changing this to:
var app = angular.module('weatherApp', []);
app.controller('weatherController', function($scope, $http) {
$scope.units = 'metric';
$scope.id = 'e08f9689f06c1b6eddb44396c749eb54';
$http.jsonp('http://api.openweathermap.org/data/2.5/weather', { params : {
q : $scope.city,
units : $scope.units,
callback: 'JSON_CALLBACK',
APPID: $scope.id
}}).success(function(data){
$scope.data = data;
});
$scope.reset = function(){
$scope.city = '';
};
});

Angular load selectlist with json from mvc controller

Here is my view:
<div>
<select ng-model="firstSupplier" ng-options="firstSupplier as firstSupplier.SupplierName for firstSupplier in jsonSuppliers"></select>
</div>
and here is my angular controller:
(function() {
var app = angular.module("CustCMS");
var indexController = function($scope, $http) {
$http.get("/Home/GetAllSuppliers")
.then(function (response) {
$scope.jsonSuppliers = response.data;
$scope.firstSupplier = $scope.jsonSuppliers[0];
});
};
app.controller("IndexController", ["$scope", "$http", indexController]);
}());
and here is my mvc controller:
public JsonResult GetAllSuppliers()
{
var suppliers = GetAll();
return Json(new { data = suppliers}, JsonRequestBehavior.AllowGet);
}
here is the json that returns to the angular controller jsonSuppliers:
{"data":[{"SupplierId":1,"SupplierName":"Normstahl","PrefixCountryCode":"NS01COUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":2,"SupplierName":"TestSupplier 2","PrefixCountryCode":null,"UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":3,"SupplierName":"Ditec","PrefixCountryCode":"DIIT01COUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":4,"SupplierName":"Ospf","PrefixCountryCode":"CRCOUNTRY","UseOrderSystem":false,"IsDirect":false,"Customers":[]},{"SupplierId":5,"SupplierName":"Alsta","PrefixCountryCode":null,"UseOrderSystem":false,"IsDirect":false,"Customers":[]}]}
Is where something that im missing here?
I don't get any errors in the console....
Is there an easier way to do it that would be much appreciated!

Categories

Resources