I'm new to AngularJS and I'm trying to get one of my routed pages to load data from a MySQL database. After looking online at a few different tutorials, I seem to be doing something wrong and can't figure out why it's not working.
INDEX PAGE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base href="/angtest/">
<title>AngularJS Test</title>
</head>
<body ng-app="myApp">
<p>
Home - About - Items
<br>
Click on the links to go to new pages.
</p>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular-route.js"></script>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(['$routeProvider','$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/", {
templateUrl : "home.html"
}).when("/home", {
redirectTo : "/"
}).when("/about", {
templateUrl : "about.html"
}).when("/items", {
templateUrl : "items.html",
controller : "usercontroller"
}).otherwise({
redirectTo : "/"
});
}]);
app.controller("usercontroller", function($scope, $http){
$http.get("select.php")
.then(function(data){
$scope.items = data;
});
});
</script>
</body>
</html>
When going to /home, /about or /items, the pages load correctly, but /items isn't grabbing the database information.
Title and description are the columns from the items table I would like shown.
ITEMS PAGE:
<h1>MySQL Database</h1>
<div ng-controller="usercontroller">
<table>
<tr>
<th>Item Name</th>
<th>Item Description</th>
</tr>
<tr ng-repeat="x in items">
<td>{{ x.title }}</td>
<td>{{ x.description }}</td>
</tr>
</table>
</div>
SELECT SCRIPT:
<?php
$connect = mysqli_connect("localhost", "USERNAME", "PASSWORD", "DBNAME");
$output = array();
$query = "SELECT * FROM items";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
}
?>
In the console window, no errors show up.
UPDATE
To check the console window, I changed my controller to:
app.controller("usercontroller", function($scope, $http){
$http.get("select.php")
.then(function(data){
console.log(data);
$scope.items = data;
});
});
The log is showing:
Item page
<h1>MySQL Database</h1> <div> <table> <tr> <th>Item Name</th> <th>Item Description</th> </tr> <tr ng-repeat="x in items"> <td>{{ x.title }}</td> <td>{{ x.description }}</td> </tr> </table> </div>
Related
Laravel 8 with User & teamwork together
I am working on data-table javascript, and controller but the error is still there, and it bugged me as I am not knowledgeable with laravel as I only work on laravel for one month (it's perfect code and way better than WordPress PHP). I look at details on google, but most of them are details write dropdowns based on the hardcode selection list.
I'm using
<label for="selectTeam">{{ __('Team')}}</label>
<select class="form-control" id="selectTeam">
#foreach($teamlistfliter as $row)
<option>{{ $row->team }}</option>
#endforeach
</select>
and it is working fine and but not related to data table show user in the list
but when I want this dropdown can query to list of users, that where it became error
here are the controller pages I wrote
class TeamUserListController extends Controller
{
public function index(Request $request)
{
if ($request->ajax())
{
$teamlistfliter = User::join('teams', 'teams.id', '=', 'users.current_team_id')
->get(['users.name as username', 'teams.name as team', 'users.firstname as first_name', 'users.surname as surname']);
return Datatables::of($teamlistfliter)
->filter(function ($instance) use ($request) {
if ($request->get('team') == '0' || $request->get('team') == '1') {
$instance->where('team', $request->get('team'));
}
if (!empty($request->get('search'))) {
$instance->where(function($w) use($request){
$search = $request->get('search');
$w->orWhere('name', 'LIKE', "%$search%")
->orWhere('email', 'LIKE', "%$search%");
});
}
})
->rawColumns(['team'])
->make(true);
}
return view('teamlistfliter');
}
}
and blade pages
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header d-block">
<div class="col-md-6">
<div class="form-group">
<label for="selectTeam">{{ __('Team')}}</label>
<select class="form-control" id="selectTeam">
#foreach($teamlistfliter as $row)
<option>{{ $row->team }}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="card-body">
<div class="dt-responsive">
<table id="simpletable"
class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</thead>
<tbody>
#foreach($teamlistfliter as $row)
<tr>
<td>{{ $row->first_name }}</td>
<td>{{ $row->surname }}</td>
<td>{{ $row->username }}</td>
<td>{{ $row->team }}</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- push external js -->
#push('script')
<script src="{{ asset('plugins/DataTables/datatables.min.js') }}"></script>
<script src="{{ asset('js/datatables.js') }}"></script>
<script type="text/javascript">
$(function () {
var table = $('#selectTeam').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('teamlistfliter.index') }}",
data: function (d) {
d.approved = $('#selectTeam').val(),
d.search = $('input[type="search"]').val()
}
},
columns: [
{data: 'firstname', name: 'firstname'},
{data: 'surname', name: 'surname'},
{data: 'username', name: 'username'},
{data: 'email', name: 'email'},
{data: 'team', name: 'team'},
]
});
$('#selectTeam').change(function(){
table.draw();
});
});
</script>
#endpush
#endsection
I fear I miss something as I assume the issue is $teamlistfilter outside the statement.
[2021-09-03 19:28:18] local.ERROR: Undefined variable: teamlistfliter (View: C:\Ergnation-rowing\resources\views\teamlistfliter.blade.php) {"view":{"view":"C:\\Ergnation-rowing\
esources\\views/teamlistfliter.blade.php","data":{"errors":"<pre class=sf-dump id=sf-dump-1080913330 data-indent-pad=\" \"><span class=sf-dump-note>Illuminate\\Support\\ViewErrorBag</span> {<a class=sf-dump-ref>#1449</a><samp data-depth=1 class=sf-dump-expanded>
#<span class=sf-dump-protected title=\"Protected property\">bags</span>: []
</samp>}
</pre><script>Sfdump(\"sf-dump-1080913330\", {\"maxDepth\":3,\"maxStringLength\":160})</script>
"}},"userId":1,"exception":"[object] (Facade\\Ignition\\Exceptions\\ViewException(code: 0): Undefined variable: teamlistfliter (View: C:\\Ergnation-rowing\
esources\\views\\teamlistfliter.blade.php) at C:\\Ergnation-rowing\
esources\\views/teamlistfliter.blade.php:45)
Try get basic value from controller and use JavaScript to write on blade pages
public function index()
{
$teamlistfliter = User::join('teams', 'teams.id', '=', 'users.current_team_id')
->get(['users.name as username', 'teams.name as team', 'users.firstname as first_name', 'users.surname as surname']);
return view('teamlistfliter', compact('teamlistfliter'));
}
and use JavaScript on blade pages
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header d-block">
<h3>{{ __('Team')}}</h3>
<div class="Team-filter">
<select id="TeamFilter" class="form-control">
<option value="">Show All</option>
#foreach($teamlistfliter as $row)
<option>{{ $row->team }}</option>
#endforeach
</select>
</div>
</div>
<div class="card-body">
<div class="dt-responsive">
<table id="filterTable"
class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</thead>
<tbody>
#foreach($teamlistfliter as $row)
<tr>
<td>{{ $row->first_name }}</td>
<td>{{ $row->surname }}</td>
<td>{{ $row->username }}</td>
<td>{{ $row->team }}</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- push external js -->
#push('script')
<script src="{{ asset('plugins/DataTables/datatables.min.js') }}"></script>
<script src="{{ asset('js/datatables.js') }}"></script>
<script>
$("document").ready(function () {
$("#filterTable").dataTable({
"searching": true
});
//Get a reference to the new datatable
var table = $('#filterTable').DataTable();
//Take the Team filter drop down and append it to the datatables_filter div.
//You can use this same idea to move the filter anywhere withing the datatable that you want.
$("#filterTable_filter.dataTables_filter").append($("#TeamFilter"));
//Get the column index for the Team column to be used in the method below ($.fn.dataTable.ext.search.push)
//This tells datatables what column to filter on when a user selects a value from the dropdown.
//It's important that the text used here (Team) is the same for used in the header of the column to filter
var TeamIndex = 0;
$("#filterTable th").each(function (i) {
if ($($(this)).html() == "Team") {
TeamIndex = i; return false;
}
});
//Use the built in datatables API to filter the existing rows by the Team column
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var selectedItem = $('#TeamFilter').val()
var Team = data[TeamIndex];
if (selectedItem === "" || Team.includes(selectedItem)) {
return true;
}
return false;
}
);
//Set the change event for the Team Filter dropdown to redraw the datatable each time
//a user selects a new filter.
$("#TeamFilter").change(function (e) {
table.draw();
});
table.draw();
});
</script>
#endpush
#endsection
that should should be working
This is what I'm looking for and thank you so much!
So I am using angularjs to display contents that are retrieved from mySQL. I am trying to create a pagination with angularjs to display them a certain amount of them at each page. My problem is that in the VIEW, it displays the contents based on the limit I defined in the controller, however, it is not displaying the page numbers that I can use to navigate through the pages. any thoughts???
Here is my code:
<!-- the VIEW -->
<div class="container testing" ng-controller="musicControl">
<table>
<tr ng-repeat="post in posts | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<td style="padding:15px">{{ post.postType }}</td>
<td style="padding:15px">{{ post.postTitle | uppercase }}</td>
<td style="padding:15px">{{ post.postDescription }}</td>
<td style="padding:15px">{{ post.postDate | date }}</td>
<td style="padding:15px">
<?php
include "functions.php";
placeMusic('{{ post.src | trustAsResourceUrl }}');
?>
</td>
</tr>
</table>
<div ng-show="filteredItems > entryLimit">
<div pagination="" page="currentPage"
on-select-page="setPage(page)"
boundary-links="true" total-items="filteredItems"
items-per-page="entryLimit"
class="pagination-small" previous-text="«"
next-text="»">
</div>
</div>
<br>
</div>
Module -->
var app = angular.module("myApp", ["ngRoute"]);
<!-- controller -->
app.controller('musicControl', function($scope, $http) {
$http.get("pages/db_section/music.php")
.then(function (response) {
$scope.posts = response.data.records;
$scope.currentPage = 1; //current page
$scope.entryLimit = 2; //max no of items to display in a page
$scope.filteredItems = $scope.posts.length; //Initially for no filter
$scope.totalItems = $scope.posts.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
});
<!-- filter -->
app.filter('trustAsResourceUrl', ['$sce', function($sce) {
return function(val) {
return $sce.trustAsResourceUrl(val);
};
}]);
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
Trying to get some data from database using Vuejs. There are some dummy data in my users table. I want to show them in my view. Problem is though the page loads, It cannot fetch the data from the users table. It does not give any console error. I have checked database connection, restarted server and also checked api data with postman. It's working fine.
Views:
layout.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="screen" title="no title">
</head>
<body>
<div class="container">
#yield('content')
</div>
<!-- scripts -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js" charset="utf-8"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.2/vue-resource.min.js" charset="utf-8"></script>
#yield('scripts')
</body>
</html>
fetchUser.blade.php
#extends('layout')
#section('content')
<div id="UserController">
<table class="table table-hover table-striped">
<thead>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
</thead>
<tbody>
<tr v-for="user in users">
<td>#{{ user.id }}</td>
<td>#{{ user.name }}</td>
<td>#{{ user.email }}</td>
<td>#{{ user.address }}</td>
<td>#{{ user.created_at }}</td>
<td>#{{ user.updated_at }}</td>
</tr>
</tbody>
</table>
</div>
#endsection
#section('scripts')
<script src="{{ asset('js/script.js') }}" charset="utf-8"></script>
#endsection
script.js
var vm = new Vue({
el: '#UserController',
methods: {
fetchUser: function(){
this.$http.get('api/users', function(data) {
this.$set('users', data )
})
}
},
ready: function(){
}
});
web.php
Route::get('/', function () {
return view('fetchUser');
});
api.php
<?php
use Illuminate\Http\Request;
use App\User;
Route::get('/users', function(){
return User::all();
});
You should use then , and call the fetchUser in the ready function as well
data:{
users: []
},
methods:{
fetchUser: function(){
this.$http.get('api/users').then(function(response){
this.$set('users', response.data);
}, function(response){
// error callback
});
},
ready: function(){
this.fetchUser();
}
vue-resource docs
im building a project with angular and php and im trying to delete a row from database table. i don't know what to do with this error can someone help please? this is my code
php for retrieve- get-allCustomers.php
<?php header('Content-Type: text/html; charset=utf-8');
$con = mysqli_connect('localhost','root','','hamatkin');
if(!$con){
die("couldnt connect".mysqli_error);
}
$query = "SELECT `customer_id`, `kind_Of_Customer`, `first_name`, `last_name`, `id`, `city` FROM `customers`";
$result = $con->query($query);
$r = array();
if( $result->num_rows>0){
while($row = $result->fetch_assoc()){
$r[] = $row;
}
}
$res = json_encode($r);
echo json_encode($res);
?>
html code for retrieveing:
<!DOCTYPE html>
<html >
<head >
</head>
<body>
<h2>כרטיסי לקוחות</h2>
<!-- לחץ לפרטי כרטיס לקוח -->
<div class="search">
<label>חיפוש:</label>
<input type="text" ng-model="search_query">
<label>מיון לפי:</label>
<select ng-model="order_query">
<option value="kind_Of_Customer" >סוג לקוח</option>
<option value="first_name">שם</option>
<option value="id">ת"ז</option>
</select>
<label>מיון הפוך:</label>
<input type="checkbox" ng-model="reverse_query" value="reverse" >
</div>
<div class="table-responsive">
<table class="customer-list table table-striped">
<thead>
<tr>
<!-- <th>#</th> -->
<th class="Column-Header">מספר לקוח</th>
<th class="Column-Header">סוג לקוח</th>
<th class="Column-Header">שם פרטי</th>
<th class="Column-Header">שם משפחה</th>
<th class="Column-Header">ת.ז</th>
<th class="Column-Header">עיר</th>
<!-- <th>כתובת</th> -->
<!-- <th>מס' טלפון</th> -->
<!-- <th>מס' טלפון 2</th> -->
<!-- <th>אימייל</th> -->
<!-- <th>פקס</th> -->
<!-- <th>הופנה דרך</th> -->
<!-- <th>הערות</th> -->
</tr>
</thead>
<tbody>
<tr ng-repeat="x in customers | filter:search_query | orderBy: order_query:reverse_query">
<!-- <td>{{$index + 1}}</td> -->
<td>{{ x.customer_id}}</td>
<td>{{ x.kind_Of_Customer}}</td>
<td>{{ x.first_name }}</td>
<td>{{ x.last_name }}</td>
<td> {{ x.id}} </td>
<td> {{ x.city}} </td>
<td><button ng-click="delete(customers.customer_id, $index)">Delete</button><td>
<!-- <td> {{ x.address}} </td> -->
<!-- <td> {{ x.phone}} </td> -->
<!-- <td> {{ x.phone_2}} </td> -->
<!-- <td> {{ x.email}} </td> -->
<!-- <td> {{ x.fax}} </td> -->
<!-- <td> {{ x.referrer}} </td> -->
<!-- <td> {{ x.comments}} </td> -->
</tr>
</tbody>
</table>
</div>
</body>
</html>
php - deleteCustomer.php :
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
$connect=mysqli_connect('localhost', 'root', '', 'hamatkin');
if(isset($_GET['customer_id'])){
$id=$_GET['customer_id'];
$del="DELETE FROM customers WHERE customer_id='".$id."'";
mysqli_query($connect,$del);
}
?>
controller - this controller get all customers table data and showing it. it works fine. the rest is what i tried for delete.:
"use strict";
angular.module('dataSystem').controller('customerCardsCtrl', function($scope,$route,$location,$http) {
$http({method:'GET', url:'api/get-allCustomers.php/'})
.then(function(response) {
var arr = JSON.parse(JSON.parse(response.data));
$scope.customers = arr;
})
// This will log you the error code and trace, if there is an error.
.catch(function(err) {
console.log('err', err)
});
$scope.delete = function(deletingId, index){
var params = $.param({"customer_id":deletingId})
$http({
url: "api/deleteCustomer.php",
method:"GET",
data:params
}).success(function(data){
$scope.customers = data;
$scope.customers.splice(index,1);
console.log(data)
});
}
Replace $scope.data.splice(index, 1); with simply data.slice(index, 1);
The data being returned doesn't live in $scope.
Initialize a $scope.variable = []; outside the scope of the function and then
.success(function(data){
$scope.variable = data;
$scope.variable.splice(index,1);
});
I think what you are trying to do in the success callback is to remove the deleted customer from the view.
Try with.
$scope.customers.splice(index,1);
in the success callback
I'm currently developing a comment function in Laravel 5. I want to display instantly the comment the user just post. So how can I achieve that? I have tried to use load() method in AJAX, but it still doesn't work.
Here is the controller to insert a comment:
public function newComment(Request $request)
{
try {
$date_format = date('Y-m-d');
$comment=new Comment();
$comment->user_id=Auth::user()->id;
$comment->introduce=$request->introduce;
$comment->completed_day=$request->completed_day;
$comment->allowance=str_replace( ',', '', $request->allowance);
$comment->post_at=$date_format;
$comment->job_id=$request->job_id;
$comment->save();
return response()->json(array('mess'=>'Success'));
}
catch (Exception $ex) {
return response()->json(array('err'=>'Error'));
}
}
Here is the view and {{$jobReply -> user -> full_name }} im using ORM to get user name
<div class="panel-body" id="job_comment_post" style="text-align:left">
<table class="table table-hover">
<thead>
<tr>
<th>Freelancer name</th>
<th>Introduce</th>
<th>Completed day</th>
<th>Allowance</th>
</tr>
</thead>
<tbody>
#foreach($job_comment as $jobReply)
<tr>
<td>{{$jobReply -> user -> full_name }}</td>
<td>{{$jobReply -> introduce}}</td>
<td>{{$jobReply -> completed_day}}</td>
<td>{{number_format($jobReply -> allowance)}}</td>
</tr>
#endforeach()
</tbody>
</table>
<div class="details_pagi">
{!! $job_comment->render() !!}
</div>
</div>
This is AJAX to insert comment:
$(document).ready(function() {
$('#btnInsertComment').click(function(event) {
event.preventDefault();
var data=$("#commentForm").serialize();
$.ajax({
url: '/postComment',
type: 'POST',
data: data,
success:function(data) {
alert(data.mess);
//job_comment_post is the div i want to load new comment
$("#job_comment_post").load();
$("#commentForm")[0].reset();
},
error:function(data) {
alert(data.err);
}
});
});
});