Click post link to display full results on another page - javascript

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

Related

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;

how to use session in angularjs

I am creating a web app in which i want to store userid and role in session through Angularjs
this is my Angularjs file
$http.get('/login.asmx/loginuser', {
params: {
log: $scope.log,
pm: $scope.pm,
password: $scope.password
}
})
.then(function (response) {
{
$scope.suc = response.data;
console.log(response.data);
if (response.data == 'success') {
console.log('success');
$window.location.href = "../welcomepage/welcometable";
}
else
{
console.log('nosuccess');
$window.location.href = "../Login/Index";
}
}
})
i need to store $scope.pm and $scope.log in my session and want to use the same on my welcome page
how to store and use sessions in angularjs?
You can use session storage or local storage for that, here is the example of session storage.
session storage or local storage will not work here in stack overflow
so refer given link.
Link
window.addCart = function($scope, $http, $window, $document){
var getValue = function(){
return $window.sessionStorage.length;
}
var getData = function(){
var json = [];
$.each($window.sessionStorage, function(i, v){
json.push(angular.fromJson(v));
});
return json;
}
$scope.images = getData();
$scope.count = getValue();
$scope.addItem = function(id){
var image = document.getElementById('img'+id);
json = {
id: id,
img: image.src
}
$window.sessionStorage.setItem(id, JSON.stringify(json));
$scope.count = getValue();
$scope.images = getData();
}
$scope.removeItem = function(id){
$window.sessionStorage.removeItem(id);
$document.
$scope.count = getValue();
$scope.images = getData();
alert('Removed with Success!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="">
<div ng-controller="addCart">
<p>{{ count }}</p>
<div>
<img id="img16" src="http://placehold.it/351x350"/>
Add to Cart
</div>
<div>
<img id="img5" src="http://placehold.it/352x350"/>
Add to Cart
</div>
<div>
<img id="img32" src="http://placehold.it/353x350"/>
Add to Cart
</div>
<div>
<img id="img43" src="http://placehold.it/354x350"/>
Add to Cart
</div>
<hr />
<table>
<thead>
<td>Image</td>
<td>Options</td>
</thead>
<tbody>
<tr ng-repeat="data in images" id>
<td><img ng-src="{{ data.img }}"/></td>
<td>Remove Item {{ data.id }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
angular.module('cookieStoreExample', ['ngCookies'])
.controller('ExampleController', ['$cookieStore', function($cookieStore) {
// Put cookie
$cookieStore.put('myFavorite','oatmeal');
// Get cookie
var favoriteCookie = $cookieStore.get('myFavorite');
// Removing a cookie
$cookieStore.remove('myFavorite');
}]);
look on

AngularJs, Ionic: $http.get does not work

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>

trying to update data in databse using Angular.js

I am trying to update data in the database using angular in Laravel 4 but the data is'nt get inserted, and a blank value is getting stored in to the database. Please find the bug and try to insert the passed value insteed of blank value.
JS File
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.updateFunction = function(updateId) {
$http.get("http://localhost/crud/public/registration_update_page/" + updateId).then(function successCallback(response) {
console.log('successCallback');
console.log(response);
alert("Row with id " + updateId + ", updated..!");
}, function errorCallback(response) {
console.log('errorCallback');
console.log(response);
});
};
});
.PHP File
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>Registration</h2><br/>
<table border=1>
<tr><td>Name:</td><td><input type="text" ng-model="nam" name="nam"><br/></td></tr>
<tr><td>Email:</td><td><input type="email" ng-model="email" name="email"><br/></td></tr>
<tr><td>Password:</td><td><input type="password" ng-model="password" name="password"><br/></td></tr>
<tr><td>City:</td><td><input type="text" ng-model="city" name="city"><br/></td></tr>
<tr><td><button ng-click="insertFunc()" type="submit">Submit</button></td></tr>
</table>
</div>
</form>
<table style="width:100%" border=1>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>City</th>
<th>Update</th>
<th>Delete</th>
</tr>
<tr ng-init='show = true' ng-repeat="x in query" ng-hide='!show'></div>
<!-- ng-hide will work when it is true in condition -->
<td>{{x.id}}</td>
<td><input type="text" value="{{x.name}}" name="edited_name"></td>
<td><input type="text" value="{{x.email}}" name="edited_email"></td>
<td><input type="text" value="{{x.password}}" name="edited_password"></td>
<td><input type="text" value="{{x.city}}" name="edited_city"></td><br/>
<td><input type="submit" ng-click="updateFunction(x.id);" value="Update"></td>
<td><button ng-click="deleteFunction(x.id);show = false">Delete</button></td>
<!-- !show==false means !false i.e., true -->
</tr><div>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function registration_update_function(Request $request)
{
$updateId = $request->id;
$edited_name = $request->edited_name;
$edited_city = $request->edited_city;
$users1 = DB::table('angular_registration')->where('id', '=', $updateId)->update(['city' => $edited_city]);
}
}
Try with post method and following code and pass full x object / scope and x.id in this function updateFunction(x, x.id);
Angular Code
var req = {
method: 'POST',
url: 'http://localhost/crud/public/registration_update_page/',
data: { x: x, id = x.id }
}
$http(req).then(function(){
//Success
}, function(){
});
On server side PHP
print_r($_POST);
I solved this problem myself
This works for ANGULAR.JS with Laravel 4 to run insert,update,delete and select queries of the MySql DataBase.
VIEW
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h2>Registration</h2><br/>
<table border=1>
<tr><td>Name:</td><td><input type="text" ng-model="nam" name="nam"><br/></td></tr>
<tr><td>Email:</td><td><input type="email" ng-model="email" name="email"><br/></td></tr>
<tr><td>Password:</td><td><input type="password" ng-model="password" name="password"><br/></td></tr>
<tr><td>City:</td><td><input type="text" ng-model="city" name="city"><br/></td></tr>
<tr><td><button ng-click="insertFunc()" type="submit">Submit</button></td></tr>
</table>
</div>
</form>
<table style="width:100%" border=1>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>City</th>
<th>Update</th>
<th>Delete</th>
</tr>
<tr ng-init='show = true' ng-repeat="x in query" ng-hide='!show'></div>
<!-- ng-hide will work when it is true in condition -->
<td>{{x.id}}</td>
<td>{{x.name}}<input type="text" ng-model="edited_name"></td>
<td>{{x.email}}<input type="text" ng-model="edited_email"></td>
<td>{{x.password}}<input type="text" ng-model="edited_password"></td>
<td>{{x.city}}<input type="text" ng-model="edited_city"></td><br/>
<td><input type="submit" ng-click="updateFunction(x.id,edited_name,edited_email,edited_password,edited_city);" value="Update"></td>
<td><button ng-click="deleteFunction(x.id);show = false">Delete</button></td>
<!-- !show==false means !false i.e., true -->
</tr><div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.deleteFunction = function(deleteId)
{
$http.get("http://localhost/crud/public/registration_delete_page/"+deleteId)
.then(function successCallback(response)
{
console.log('successCallback');
console.log(response);
alert("Row with id "+deleteId+", deleted..!");
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
};
$scope.updateFunction = function(updateId,edited_name,edited_email,edited_password,edited_city)
{
$http.get("http://localhost/crud/public/registration_update_page/"+updateId+"/"+edited_name+"/"+edited_email+"/"+edited_password+"/"+edited_city)
.then(function successCallback(response)
{
//$scope.edited_name = edited_name;
console.log('successCallback');
console.log(response);
alert("Row with id "+updateId+", updated..!");
},
function errorCallback(response)
{
console.log('errorCallback');
console.log(response);
});
};
$scope.insertFunc = function() {
$http({
method : 'POST',
url : 'http://localhost/crud/public/registration_data_page',
data : {nam:$scope.nam,email:$scope.email,password:$scope.password,city:$scope.city}
}).then(function successCallback(response) {
console.log('successCallback');
console.log(response);
}, function errorCallback(response) {
console.log('errorCallback');
console.log(response);
});
}
$http({method:'GET', url:'http://localhost/crud/public/registration_json_page'}).success(function(response){
$scope.query = response;
});
});
</script>
</body>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Session;
use Redirect;
class NewController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function registration_data_function(Request $request)
{
echo $nam_value = $request->nam;
echo $email_value = $request->email;
echo $password_value = $request->password;
echo $city_value = $request->city;
$reg = DB::table('angular_registration')->insert(['name' => $nam_value, 'email' => $email_value, 'password'=>$password_value, 'city'=>$city_value]);
}
public function registration_json_function(Request $request)
{
$query = DB::select('select * from angular_registration');
return response($query);
}
public function registration_function(Request $request)
{
$query = DB::select('select * from angular_registration');
return view('registration');
}
public function registration_delete_function(Request $request)
{
$deleteId = $request->id;
return $users = DB::table('angular_registration')->where('id', '=', $deleteId)->delete();
}
public function registration_update_function(Request $request)
{
echo $updateId = $request->id;
echo $edited_name = $request->edited_name;
echo $edited_email = $request->edited_email;
echo $edited_password = $request->edited_password;
echo $edited_city = $request->edited_city;
$users1 = DB::table('angular_registration')->where('id', '=', $updateId)->update(['name' => $edited_name,'email' => $edited_email,'password' => $edited_password,'city' => $edited_city]);
}
}
ROUTE
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::get('/registration', 'NewController#registration_function');
Route::post('/registration_data_page', 'NewController#registration_data_function');
Route::get('/registration_json_page', 'NewController#registration_json_function');
Route::get('registration_delete_page/{id}', 'NewController#registration_delete_function');
Route::get('registration_update_page/{id}/{edited_name}/{edited_email}/{edited_password}/{edited_city}', 'NewController#registration_update_function');

Populate table data with $http.get on dropdown option selected in Angular

I am new to Angular and would like to learn how to accomplish this task below:
I have a dropdown that contains a list of table names from a database. When a table name is selected from the drop down I want to make an HTTP GET call to a web API method which returns the list of column names in the selected table.
HTML:
<div class="row">
<div ng-app="myApp">
<div class="col-lg-12">
<h1>Table Information</h1>
<hr />
<div ng-controller="TableController" class="col-lg-6">
<label>Select a Table:</label>
<select id="tablename" ng-options="table.Name for table in tables track by table.Name" ng-model="data.selectedOption" class="form-control"></select>
</div>
</div>
<div class="col-lg-12">
<h1>{{data.selectedOption}}</h1>
<hr />
<div ng-controller="TableColumnController" class="col-lg-6">
<table class="table">
<thead>
<tr>
<th>Column Name</th>
<th>Type</th>
<th>Max Characters</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tablecolumn in tablecolumns">
<td>
{{tablecolumn.Name}}
</td>
<td>
{{tablecolumn.Type}}
</td>
<td>
{{tablecolumn.MaxCharacters}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Here is my JavaScript:
var app = angular.module('myApp', []);
app.controller('TableColumnController', function ($scope, $http) {
$http.get('http://localhost:61475/api/SxTableInfo/',
{
params: {
tablename: "smsn"
}
}).
success(function (data, status, headers, config) {
$scope.tablecolumns = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});
});
app.controller('TableController', function ($scope, $http) {
$http.get('http://localhost:61475/api/SxTableInfo/').
success(function (data, status, headers, config) {
$scope.tables = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});
});
What is the best way to do this?
Here is just an example of what it looks like:
UPDATED CODE:
<div class="row" ng-app="myApp">
<div ng-controller="ctrl">
<div class="col-lg-12">
<h1>Table Information</h1>
<hr />
<div class="col-lg-6">
<label>Select a Table:</label>
<select id="tablename"
ng-options="table.Name for table in tables track by table.Name"
ng-model="data.selectedOption"
ng-change="getColumns(data.selectedOption)"
class="form-control"></select>
</div>
</div>
<div class="col-lg-12">
<h1>{{data.selectedOption.Name}}</h1>
<hr />
<div class="col-lg-6">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Column Name</th>
<th>Type</th>
<th>Max Characters</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tablecolumn in tablecolumns">
<td>
{{tablecolumn.Name}}
</td>
<td>
{{tablecolumn.Type}}
</td>
<td>
{{tablecolumn.MaxCharacters}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
var app = angular.module('myApp', []);
app.factory('tableService', ['$http', function ($http) {
function getColumns(selection) {
$http.get('http://localhost:61475/api/SxTableInfo/', { params: { tablename: selection } }).success(function (data) {
return data;
});
}
function getTables() {
$http.get('http://localhost:61475/api/SxTableInfo/').success(function (data) {
return data;
});
}
return { getColumns: getColumns, getTables: getTables }
}]);
app.controller('ctrl', ['$http', '$scope', 'tableService', function ($http, $scope, tableService) {
$scope.tables = tableService.getTables();
$scope.getColumns = function (selection) {
$scope.tablecolumns = tableService.getColumns(selection.Name);
}
}]);
</script>
}
No need for multiple controllers, and you'll need to bind to ngChange. Observe the following example, specifically, the binding to getStuff...
<select
id="tablename"
ng-options="table.Name for table in tables track by table.Name"
ng-model="data.selectedOption"
ng-change="getStuff(data.selectedOption)"
class="form-control">
</select>
app.controller('ctrl', function ($scope, $http) {
$scope.getStuff = function(selection) {
$http.get('http://localhost:61475/api/SxTableInfo/', {
params: { tablename: selection }
})
.success(function (data, status, headers, config) {
$scope.tablecolumns = data;
});
}
}
I would recommend moving this logic into an injectable service, most likely your next step. Something like...
app.factory('TableService', ['$http', function($http) {
function getMetaData(selection) {
$http.get('http://localhost:61475/api/SxTableInfo/', { params: { tablename: selection } }
}
return { getMetaData: getMetaData }
}]);
app.controller('ctrl', ['$scope', 'TableService', function ($scope, TableService) {
$scope.getStuff = function(selection) {
TableService.getMetaData(selection).then(function(response) {
$scope.tablecolumns = response.data;
});
}
}]);
Plunker Link - simplified demo
Edit per your example and updated code, give this a shot...
app.controller('ctrl',...
tableService.getTables().then(function(response) {
$scope.tables = response.data;
});
$scope.getColumns = function (selection) {
tableService.getColumns(selection.Name).then(function(response) {
$scope.tablecolumns = response.data
});
}
You should not use two controllers for this purpose, instead you can use a service or factory for $https request to get you data from the server.
You should also use ng-change to invoke table column name info call
Try this
in app.js
var app = angular.module('plunker', []);
app.factory('userFactory', ['$http', function($http) {
var dataFactory = {};
dataFactory.getTableNames = function() {
/*$http.get('http://localhost:61475/api/SxTableInfo/').
success(function (data, status, headers, config) {
$scope.tables = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});*/
data = [{
id: 1,
tableName: 'table1'
}, {
id: 2,
tableName: 'table2'
}, {
id: 3,
tableName: 'table3'
}];
return data;
}
dataFactory.getColumnNames = function() {
alert('implement your logic here . ');
/* $http.get('http://localhost:61475/api/SxTableInfo/',
{
params: {
tablename: "smsn"
}
}).
success(function (data, status, headers, config) {
$scope.tablecolumns = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});*/
}
return dataFactory;
}]);
app.controller('MainCtrl', ['$scope', 'userFactory', function($scope, userFactory) {
$scope.name = 'World';
$scope.items = userFactory.getTableNames();
$scope.getColumnNames= function(){
userFactory.getColumnNames();
}
}]);
in HTML,
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" data-semver="1.4.6"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<select ng-change="getColumnNames()" ng-model="selectedItem" ng-options="item.tableName as item.tableName for item in items"></select>
</body>
</html>
Plunker link for the same.

Categories

Resources