Always get NULL when getting the selected value from dropdown Laravel - php

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

Related

Search option in product dropdown in Laravel

I have successfully done the product dropdown list with the select option but I am can't include the search option inside the dropdown. I have tried some code taken from Google but failed. I am new to Laravel and I don't know how to proceed further. Please help to include the search option.
Here is the code!
Blade:
<div class="row">
<div class="input-field col s12 m6">
{{ Form::select('customer', $customers, null, ['placeholder' => 'Select A Client ID' ,'required'=> '', 'aria-required' => 'true']) }}
</div>
<div class="input-field col s12 m6">
{{ Form::select('products[]', $products, null, ['multiple' => true, 'class' => 'validate multiple', 'required'=> '', 'aria-required' => 'true']) }}
</div>
</div>
Controller:
public function add()
{
$title = "Add New Order";
$customer_list = DB::table('accounts')->select('id', 'fname', 'lname')->where('account_type_id', '1')->get();
$product_list = DB::table('products')->select('id', 'name', 'quantity')->where('status', 1)->where('show_client', 1)->where('quantity', '>', 0)->get();
$customers = array();
foreach ($customer_list as $customer) {
$customers[$customer->id] = $customer->id;
}
$productss = array();
foreach ($product_list as $product) {
$productss[$product->id] = $product->name . " (" . $product->quantity . ")";
}
$pselect = array('value="" disabled selected' => 'Please Select Products');
$products = $pselect + $productss;
return view('order.add', compact('title', 'customers', 'products'));
}
Route:
// Orders Controller
Route::get('/order', 'OrderController#manage');
Route::get('/order/add', 'OrderController#add');
Route::post('/order/add_confirm', 'OrderController#addConfirm');
Route::post('/order/add_confirmed', 'OrderController#addConfirmed');
Route::get('/order/manage/{id}', 'OrderController#manageOrder');
Route::post('/order/manage/accept', 'OrderController#manageOrderStatus');
Route::post('/order/manage/pending', 'OrderController#manageOrderStatus');
Route::post('/order/manage/cancel', 'OrderController#manageOrderStatus');
Route::post('/order/manage/fraud', 'OrderController#manageOrderStatus');
Route::post('/order/manage/delete', 'OrderController#manageOrderStatus');
Route::post('/order/save_note', 'OrderController#manageOrderNote');
Route::post('/order/emi_calculation', 'OrderController#emiCalculation');
Route::get('/order/{name}', 'OrderController#manage');
Generally, avoid using the Form Helpers ie. {{ Form:: ... because they make the code too complicated and long without any real advantages. Use normal simple html form tags.
To search customers, try to use DATALIST HTML element but not the select. See here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist
To populate the datalist with a default value, eg. select a customer, use its value property as shown below.
The following should work.
The web.php
Route::get('/order/add', 'OrderController#add'); //testing
The OrderController.php . Note I have just changed your initial queries for product and customers (my customers table is called partners) a bit to match my database tables and columns but the logic is still intact.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OrderController extends Controller
{
//
public function add()
{
$title = "Add New Order";
// $customers = DB::table('accounts')->select('id', 'fname', 'lname')->where('account_type_id', '1')->get();
$customers = DB::table('partners')/*->select('id', 'fname', 'lname')->where('account_type_id', '1')*/->get();
//$products = DB::table('products')->select('id', 'name', 'quantity')->where('status', 1)->where('show_client', 1)->where('quantity', '>', 0)->get();
$products = DB::table('products')/*->select('id', 'name', 'quantity')->where('status', 1)->where('show_client', 1)->where('quantity', '>', 0)*/->get();
return view('order.add', compact('title', 'customers', 'products'));
}
}
The views/add.blade.php is as below.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="input-field col s12 m6">
<input class="customers" list="customers" name="customer" value="Select A Customer" required>
<datalist id="customers">
#foreach($customers as $customer)
<option value="{{$customer->name}}" data-lname="{{$customer->name}}"
data-fname="{{$customer->name}}">
</option>
#endforeach
</datalist>
</div>
</div>
<div class="col-md-6">
<div class="input-field col s12 m6">
<label for="products">Add the new Products</label>
<select multiple class="form-control" id="products" name="products[]" required>
<option selected disabled value="Please select Products">Please select Products</option>
#foreach($products as $product)
<option value="{{$product->name .'('. $product->quantity .')'}}"
data-quantity="{{$product->quantity}}">{{$product->name .'('. $product->quantity .')'}}
</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous">
</script>
<!-- Option 2: jQuery, Popper.js, and Bootstrap JS
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
-->
</body>
</html>
Results:
I would suggest using something that already exists, Select2 is a package I've used for a long time and its really good
heres the link to their page : https://select2.org
all you have to do is include CSS and JS
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
then your html should be like this :
<select class="js-example-basic-single" name="state">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
and your JS:
// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
$('.js-example-basic-single').select2();
});

search function from the database in laravel 5.8

This search function does not work yet. I don't know what the reason is.
Can anyone help me to find the mistake?
This is in the studentcontroller
public function testsearch()
{
$q = Input::get ( 'q' );
if($q != ""){
$student = Student::where ( 'uniid', 'LIKE', '%' . $q . '%' )->get();
if (count ( $student ) > 0)
return view ( 'Searchstudent' )->withDetails ( $student )->withQuery ( $q );
else
return view ( 'Searchstudent' )->withMessage ( 'No Details found. Try to search again !' );
}
return view ( 'Searchstudent' )->withMessage ( 'No Details found. Try to search again !' );
}
and this is Searchestudant.blade.php
<html>
<head>
<title>Search</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<form action="/Searchstudent" method="POST" role="Searchstudent">
<div class="input-group">
<input type="text" class="form-control" name="q"
placeholder="Search sickleave number"> <span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<div class="container">
#if(isset($students))
<table class="table table-striped">
<thead>
<tr>
<th>unique id</th>
<th>student_id</th>
</tr>
</thead>
<tbody>
#foreach($students as $student)
<tr>
<td>{{$student->uniid}}</td>
<td>{{$student->student_id}}</td>
</tr>
#endforeach
</tbody>
</table>
#elseif(isset($message))
<p>{{ $message }}</p>
#endif
</div>
</body>
</html>
and this is the route
```Route::get('/searechstudent','StudentController#testsearch'); ```
The error shows when I run this function:
MethodNotAllowedHttpException No message
You have mismatched your routing between your blade form and your routes file. In your blade you have called POST:
<form action="/Searchstudent" method="POST" role="Searchstudent">
With Laravel, it must match in the routing file. In your web.php file (routing) you are accepting a GET response:
Route::get('/searechstudent','StudentController#testsearch');
Change the route to a POST response:
Route::post('/searechstudent','StudentController#testsearch');
Also, it may help you to look at the PHP method compact() for your return variables from your controller in the testsearch() method - it keeps things consistent and easy to read.
Be aware of your route address, it must be exact route as you called in form. Capital character is different with normal character
Route::post('/Searchstudent','StudentController#testsearch');

Symfony - Ajax Select

I am working on a Symfony project where I have a product entity and I need an Ajax search bar to search for through my products and select some of them. The problem is I have a search bar which gives me live results from the database but if I select the product it should show the data in my table. For some reason I am not able to show the selected results in my table.
js
$('.js-data-example-ajax').select2({
ajax: {
url: '/product/api/search',
dataType: 'json',
}
});
Controller
public function viewActionSearch(Request $request)
{
$query = $request->get('term');
$result = [
'results' => [],
];
if ($query !== null){
$products = $this->productRepository->getSearchList($query);
$result['results'];
foreach ($products as $product) {
$result['results'][] = [
'id' => $product['id'],
'text' => $product['name'],
];
}
} else {
$products = $this->productRepository->getResultList(1);
foreach ($products as $entity) {
$result['results'][] = [
'id' => $entity['id'],
'text' => $entity['name'],
];
}
}
return new JsonResponse($result);
}
ProductList
public function getPage(Request $request)
{
$products = $this->productRepository->getAllProducts($currentPage);
return $this->render(
'#app_bar/Product/productList.twig',
[
'products' => $products,
]
);
}
Twig
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- select2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/gh/ttskch/select2-bootstrap4-theme#master/dist/select2-bootstrap4.min.css" rel="stylesheet">
<div class="container mt-5">
<form>
<div class="form-group">
<select class="js-data-example-ajax form-control"></select>
</select>
</div>
</form>
</div>
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>id</th>
<th>Title</th>
<th>SKU</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>
{{ product.id }}
</td>
<td>
{{ product.name }}
</td>
<td>
{{ product.sku }}
</td>
<td>
<a href="{{ path('app_product_getproduct', {'id': product.id}) }}" class="btn btn-success btn-sm" >
<span class="glyphicon glyphicon-pencil"></span>
</a>
<a href="{{ path('app_product_delete', {'id': product.id}) }}" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')">
<span class="glyphicon glyphicon-trash"></span>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
If I visit the route /product/api/search/ it's giving my a result back but i am not able to show these selected products in my table.
You missing something here. Symfony does not work like frontend frameworks like vue.js or similar. What you are doing you are rendering serverside request and after that, you just fetch data via AJAX and you do nothing with that data. jQuery needs instructions on what to do with data you get from the server. You can always use Symfony alongside some frontend framework, but you need to understand the difference when serverside renders your twig template and when frontend framework renders it.
http://api.jquery.com/jquery.ajax/
Hint:
$('.js-data-example-ajax').select2({
ajax: {
url: '/product/api/search',
dataType: 'json',
success: function (data) {
$.each(response, function () {
$('#mytable').append('<tr><td>' + this.product_name + '</td><td>' + this.product_price + '</td></tr>');
});
}
}
});
There are different methods of what you can render, you can reload whole table or just rows that you need.

Laravel 5.3 with Vuejs ajax call

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

Cannot read property 'splice' of undefined?

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

Categories