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
Related
With my current Laravel project I am using (attempting) both Bootstrap and MDBoostrap. Currently, I'm getting the error TypeError: $(...).DataTable is not a function and from reading up on this online, this is usually due to jquery being called multiple times. I believe the error has to do with app.js but if I only include the scripts Bootstraps requires for a datatable I get the error that $ is undefined. Note: index.blade.html is extending from app.blade.html. With Laravel, I'm only trying to use MDB to create a datatable. This may be a duplicate from here but this question never got answered. I've been banging my head on this problem for a whole day now, any input is appreciative.
app.blade.html
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{asset('css/app.css')}}">
<title>Laravel Project</title>
</head>
<body>
<div class="container">
#yield('content')
</div>
<script src="{{asset('js/app.js')}}"></script>
<script>
// Material Design example
$(document).ready(function () {
$('#dtMaterialDesignExample').DataTable();
$('#dtMaterialDesignExample_wrapper').find('label').each(function () {
$(this).parent().append($(this).children());
});
$('#dtMaterialDesignExample_wrapper .dataTables_filter').find('input').each(function () {
const $this = $(this);
$this.attr("placeholder", "Search");
$this.removeClass('form-control-sm');
});
$('#dtMaterialDesignExample_wrapper .dataTables_length').addClass('d-flex flex-row');
$('#dtMaterialDesignExample_wrapper .dataTables_filter').addClass('md-form');
$('#dtMaterialDesignExample_wrapper select').removeClass('custom-select custom-select-sm form-control form-control-sm');
$('#dtMaterialDesignExample_wrapper select').addClass('mdb-select');
$('#dtMaterialDesignExample_wrapper .mdb-select').materialSelect();
$('#dtMaterialDesignExample_wrapper .dataTables_filter').find('label').remove();
});
</script>
</body>
</html>
index.blade.html
#extends('layouts.app')
#section('content')
<h1>User Table</h1>
#if(count($users) > 0)
<table id="dtMaterialDesignExample" class="table" cellspacing="0" width="100%">
<thead>
<tr>
<th class="th-sm">ID
</th>
<th class="th-sm">Name
</th>
<th class="th-sm">Occupation
</th>
<th class="th-sm">Location
</th>
<th class="th-sm">Salary
</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->occupation}}</td>
<td>{{$user->location}}</td>
<td>{{$user->salary}}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
#endsection
UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = User::orderBy('id', 'asc')->paginate(10);
return view('users.index',['users'=>$users]);
}
bootstrap.js
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
require('mdbootstrap');
} catch (e) {}
app.js
require('./bootstrap');
var moment = require('mdbootstrap');
app.scss
// Fonts
#import url('https://fonts.googleapis.com/css?family=Nunito');
// Variables
#import 'variables';
// Bootstrap
#import '~bootstrap/scss/bootstrap';
// MDBootstrap
#import '~mdbootstrap/css/mdb.min.css';
If this is the DataTables.net package I believe you have to include JS and possibly the CSS in order to have $('#dtMaterialDesignExample').DataTable(); succeed. I know those do not come with Bootstrap out of the box. I have a Laravel package using vanilla Bootstrap and I had to include the JS and CSS to render data tables.
I'm not terribly familiar with MDB. They may provide CSS, but I don't know if they provide the JS. It doesn't appear that you should have a duplicate definition so you need to make sure you're app is rendering something like the following to the browser:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"/>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js" type="text/javascript"></script>
That would include the JS definition of the DataTable() function.
I'm trying to get the selected value from a dropdown in my view through my controller, but it's always returning null. I really don't know why.
Here is my select dropdown:
UPDATED: Here is my full blade view!
#extends('backpack::layout')
#section('header')
<section class="content-header">
<h1>
<span class="text-capitalize">Thành tích tốt nhất ngày</span>
</h1>
<ol class="breadcrumb">
<li>Admin</li>
<li>Thành tích tốt nhất ngày</li>
<li class="active">List</li>
</ol>
</section>
#endsection
#section('content')
<form method="GET">
Lọc round:
<select id="tablefilter" name="tablefilter">
<option value="0">Hiện tại</option>
#foreach($max as $item)
<option value="{{$item->countRound}}">{{$item->countRound}}</option>
#endforeach
</select>
</form>
<table id="currentRound" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Câu lạc bộ</th>
<th>Quãng đường</th>
<th>Quãng đường trung bình</th>
<th>Xếp hạng</th>
<th>Số thành viên</th>
<th>Ngày xếp hạng</th>
</tr>
</thead>
<tbody>
#foreach ($result as $item)
<tr>
<td>{{$item->name}}</td>
<td align="right">{{number_format($item->total_distance/1000, 2)}} km</td>
<td align="right">{{number_format($item->avg_distance/1000, 2)}} km</td>
<td align="right">{{number_format($item->rank)}}</td>
<td align="right">{{$item->total_member}}</td>
<td>{{$item->created_at}}</td>
</tr>
#endforeach
</tbody>
</table>
<script>
$(document).ready(function () {
$('#currentRound').DataTable({
"paging" : true,
"aaSorting": [[3, 'asc']],
"dom": '<"top"f>rt<"bottom"lp><"clear">',
});
});
</script>
#endsection
#section('after_styles')
<!-- DATA TABLES -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<!-- CRUD LIST CONTENT - crud_list_styles stack -->
#stack('crud_list_styles')
#endsection
#section('after_scripts')
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap.min.js"></script>
#endsection
And in my controller:
public function index(Request $request) {
$round = $request->input('tablefilter');
//dd($round);
$mMile = new MilestoneEarth();
$max = $mMile->getRound();
return view('admin.cacheClubEarth.index',['result' => $result, 'max' => $max]);
}
It's return [] with $request->all() and null with $request->tablefilter
I really don't know how to do with this!
Can you help me!
Thank you very much!
You can do : dd(request->all()); for check the data.
I think you don't have to use the input function. Try this :
$round = $request->tablefilter;
you need to send the form value either submit using button or use ajax for it
here the basic submitting data via form (i specified action in case you go to different page)
<form method="GET" action="{{url('/to/index/controller/you-want')}}>
Lọc round:
<select id="tablefilter" name="tablefilter">
<option value="0">Hiện tại</option>
#foreach($max as $item)
<option value="{{$item->countRound}}">{{$item->countRound}}</option>
#endforeach
</select>
<button class="something">Update</button>
</form>
#foreach($max as $item)
<option value="{{$item}}">{{$item}}</option>
#endforeach
I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:
jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send # jquery.min.js:4 ajax # jquery.min.js:4 (anonymous) # (index):39 dispatch # jquery.min.js:3 r.handle # jquery.min.js:3
This is the code for controller called SearchController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function index()
{
return view('search.search');
}
public function search(Request $request)
{
if($request->ajax())
{
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products)
{
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
}
Code in web.php
Route::get('/','SearchController#index');
Route::get('/search','SearchController#search');
Code of blade file
<!DOCTYPE html>
<html>
<head>
<meta id="token" name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search"></input>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
It should display the record when the key is pressed but it gives error 500 internal server error
Screenshot with GET method
AJAX ERROR WITH GET
Screenshot with POST method
AJAX ERROR WITH POST
Try this
<script type="text/javascript">
$('#search').on('keyup',function(){
value=$(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url : '{{ url('search') }}',
method : 'POST',
data:{'search': value},
success:function(response){
console.log(response.data)
}
});
})
</script>
your route
Route::post('/search','SearchController#search');
and in your controller, verify
public function search(Request $request)
{
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
return response()->json(['data' => $products]);
}
The problem is, There is no DB imported.
So Just write
use DB;
in the controller
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>
I want to print the content of laravel blade file....file contains the html table of users...when user click on print button it must redirect to pop up window of print... Please help to resolve this issue.
Current code of reading the content of file...i don't know how to give the path of this file.....file is in resource/views/reports/table.blade.php
Current code shows me exception:
FileNotFoundException in Filesystem.php line 41:
File does not exist at path printview_table
Code in Controller
public function printfile()
{
$filename = '/reports/printview_table.blade.php';
try
{
$contents = File::get($filename);
printfile($contents);
}
catch (Illuminate\Filesystem\FileNotFoundException $exception)
{
die("The file doesn't exist");
}
}
I know it's too late to answer but I did the same thing today and decided to post my solution here as well so that it might help someone in the future.
Required Tools:
jQuery
jQuery.print
Solution Steps:
Step 1: The view where the print button is located in.
dashboard.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Document</title>
</head>
<body>
<button id="print"> Print </button>
<script src="{{ asset('js/jquery.js') }}"></script>
<script src="{{ asset('js/jquery.print.js') }}"></script>
<script src="{{ asset('js/scripts.js') }}"></script>
</body>
</html>
Step 2: The view that is going to be printed.
Assume I have a view like this and I want to print this out:
print.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
</tbody>
</table>
</body>
</html>
Step 2: The route.
We need a route to call our view through that.
web.php
Route::post('/print', function() { return view('print'); });
Step 3: The jQuery script.
We are going to call the view content by AJAX and pass it to the jQuery.print() function for printing.
scripts.js
$('#print').on('click', function() {
let CSRF_TOKEN = $('meta[name="csrf-token"').attr('content');
$.ajaxSetup({
url: '/print/',
type: 'POST',
data: {
_token: CSRF_TOKEN,
},
beforeSend: function() {
console.log('printing ...');
},
complete: function() {
console.log('printed!');
}
});
$.ajax({
success: function(viewContent) {
$.print(viewContent); // This is where the script calls the printer to print the viwe's content.
}
});
});
That's all, customize the codes according to your own requirements.
Why don't you just pass this task to JS. In the view add a btn and on the click event call the print func.
window.print();
https://www.w3schools.com/jsref/met_win_print.asp