I have a users' data table and im trying to change role of them by populating roles from database to datatable. I use ajax to change the role and it works. but problem is value of selecting option from dropdown is not sent to database.
Herewith I attached my controller function view and ajax code.
Please advise me to solve this.
Controller:
public function changeRole(Request $request){
$id = Input::get('id');
$isAdmin = Input::get('isAdmin');
User::findOrFail($id)->update(['isAdmin'=>$isAdmin]);
}
Ajax :
$(document).ready(function(){
$('select').on('change' , function (event){
id = $(this).data('id');
isAdmin = $('#role').val();
//alert(role);
$.ajax({
type: 'POST',
url: SITE_URL + '/changeRole/',
data: {
'_token': $('input[name=_token]').val(),
'id': id,
'isAdmin': isAdmin
},
cache: false,
success: function(data) {
toastr.success('Admin Role Successfully Changed ! ', 'Congratulations', {timeOut: 5000});
//$('#example1').DataTable().ajax.reload();
},
error: function (jqXHR, exception) {
console.log(jqXHR);
toastr.error('Something Error !', 'Status not Changed!')
},
});
});
});
View :
<td>
<form method="post">
{{ csrf_field() }}
<div class="form-group">
<select class="form-control" data-id="{{$user->id}}" id="role" name="role">
<option value="0">Select a Role</option>
#foreach ($roles as $role)
<option #if($user->isAdmin==$role->id) selected #endif value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
</select>
</div>
</form>
</td>
Please see the user table view
First of all don't use Input::get('id') use $request->id and $request->isAdmin
Try dd($request->all()) at the very first line of you changeRole() method and check if you are getting the correct values every time.
Don't use $('select') give your select some id and use it as $('#myselect')
add var before you variable in jquery like var id=$() to keep it in local scope.
for reference must read this : https://www.tutorialspoint.com/What-is-the-difference-between-global-and-local-Variables-in-JavaScript
Don't use var id = $(this).data('id'); the .data() messes things up sometimes.
Use it as
var id = $(this).attr('data-id');
To get the value of selected roles use following:
var isAdmin = $(this).children("option:selected").val();
Hope this fixes many things.
Related
When I click on all of my edit buttons the first time then it populates into the city field and area field nicely. But when I clicked on the edit button a second time the city field does not populate. After refreshing its populate again with the same problem. I need help.
City field code:
<select class="form-control" id="selectCity">
<option value="0" selected disabled>--- Select City ---</option>
#foreach ($cities as $city)
<option value="{{ $city->id }}">{{ $city->city_name }}</option>
#endforeach
</select>
My Ajax code:
$(document).on('click', '#edit_area', function(e) {
e.preventDefault();
$('#addArea').hide();
$('#updateArea').show();
var area_id = $(this).val();
$.ajax({
type: "GET",
url: "/edit-area/" + area_id,
success: function(response) {
if (response.status == 400) {
//some staff goes here
} else {
$('#area_id').val(area_id);
$('#areaName').val(response.area[0].area_name);
$('#selectCity').find("option:contains(" + response.area[0].city_name + ")").attr('selected', 'selected');//this works more better
}
}
});
});
I have a list of competitions in my select option,
I need to know how can make this functionality work,
When a user selects a competition the page should reload with the competition data,
This is the select option in my blade
<div class="row pt-3">
<div class="col">
<select name="competition" id="competitionSearch" class="select listing pt-2 pb-2" >
<option value="">Select Competition</option>
#foreach ($allCompetitions as $competition)
<option value="{{ $competition->id }}"> {{ $competition->name }}</option>
#endforeach
</select>
</div>
</div>
this is how it looks like
this is the ajax get method i have used
$(document).ready(function(){
$('#competitionSearch').change(function(){
var compid = $(this).val();
if(compid > 0){
fetchRecords(compid);
}
});
});
function fetchRecords(id){
$.ajax({
url: 'detailed-registrations/getCompetitionAjax/'+id,
type: 'get',
success: function(response){
if (response) {
//load selected competition here
}
}
});
}
My routes
Route::get('competitions/{competition}/detailed-registrations/getCompetitionAjax/{id}','CompetitionController#getCompetitionAjax');
My function in the controller
public function getCompetitionAjax($competition, $id, Request $request)
{
$comp = $this->competitionsRepo->findOrFail($id);
return redirect(route('competitions.detailed-registrations',$id))->with('comp',$comp);
}
I need to know how can i make this functionality work
initially the user will be in a competition page
http://127.0.0.1:8000/competitions/1/detailed-registrations
once he selects the competition 2 redirected to the competition page with the filtered query parameters as
http://127.0.0.1:8000/competitions/2/detailed-registrations?filters=visible&age=all&gender=all
Don't think you need an ajax call for redirecting the user to a different page when a competition is selected, you can redirect from javascript
$(document).ready(function(){
$('#competitionSearch').change(function(){
var compid = $(this).val();
if(compid > 0){
//Redirect the user to the page which will show the selected details
location = 'competitions/' + id + '/detailed-registrations?filters=visible&age=all&gender=all';
}
});
});
And then let the Laravel controller method handle the request to the route competitions.detailed-registrations
Select2 is not working. I don't see any effect. I need to apply "Multi-select boxes (pillbox)" style From Select2.
I am using bootstrap 4. I think this is the problem.
What I have tried so far is showed below,
PHP
<div class="form-group" >
<label for="exampleFormControlInput">Tags</label>
<select multiple class="form-control tags"> > <!-- Multiple To Select more than one but need press ctrl+select -->
#foreach ($tags as $tagname)
<option>{{$tagname->tag}}</option>
#endforeach
</select>
Script
<script type="text/javascript">
${(function() {
$('.tags').select2();
});
</script>
First make sure you have imported the css and the javascript file
This is my view, I used select2 in my vendor.
<label>Vendor <span style="color: red">*</span></label>
<select class="form-control" name="vendor_id" required="required" id="vendor">
<option value="">Select Vendor</option>
#if($vendors)
#foreach($vendors as $key => $value)
<option value="{{ $value->id }}">{{ $value->name }}</option>
#endforeach
#endif
</select>
As you can see I declared an id because I will use it in my select2. See my code below how I implement the select2 in my vendor.
$('#vendor').select2({
placeholder: "Select Vendor" // you can change this
});
And if you want some event with that select2 here my code.
$(document).on('select2:select', '#vendor', function(e){
var id = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
url: '/purchases/purchase-orders/getVendorTerms',
type: "POST",
data: {id:id},
success: function(response) {
if (response != '') {
$('#terms').val(response.term);
}else{
$('#terms').val('');
}
editGetGoodThru();
}
});
})
Select2 depends on the order of js included, try including them in order below.
Like jQuery ->jQuery UI -> Bootstrap -> Select2.
I am trying to get dependant select items using ajax call. After selecting 'class' it should show the related 'groups'. But, I am getting 500 internal server error on my console. Would someone help me please to get the expected result?
admission-form.blade.php -
<form action="{{ route('admin.students.admission') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-6">
<div class="form-group {{ $errors->has('first_admission_class') ? 'has-error' : '' }}">
<select class="form-control" name="first_admission_class" id="first_admission_class">
<option value="">Select Class</option>
#foreach($classes as $class)
<option value="{{ $class->id }}" {{ (old("first_admission_class") == $class->id ? "selected":"") }}>{{ $class->class_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group {{ $errors->has('first_admission_class_group') ? 'has-error' : '' }}">
<select class="form-control" name="first_admission_class_group">
</select>
</div>
</div>
</div>
</form>
Script for Ajax call:
<script>
$('#first_admission_class').on('change', function(e){
console.log(e);
var class_id = e.target.value;
$.get('http://localhost/school/public/admin/ajax-group/' + class_id, function(data){
console.log(data);
});
});
</script>
web.php -
Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => 'auth:admin'], function () {
Route::get('ajax-group/{id}', function(){
$class_id = Input::get('class_id');
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
});
your route is look like this, when we add param in route they accessible via function param. i hope it works for you.
Route::get('ajax-group/{id}', function($id){
$groups = AvailableclassGroup::where('availableclass_id', '=', $id)->get();
return Response::json($groups);
});
});
you can check laravel doc Laravel route doc
if still it didnot work then
add csrf token, like this in head of your html layout
<meta name="csrf-token" content="{{ csrf_token() }}">
and make your ajax call like this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
type: 'get',
url: '/ajax-group/'+ class_id,
dataType: 'json',
success: function (data) {
},
error: function (data) {
console.log('Error:', data);
}
});
Your wildcard its named id and you are getting as class_id so change :
And make sure your route its named as admin.students.admission
Route::get('ajax-group/{id}', function(){
$class_id = Input::get('id');
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
})->name('admin.students.admission');
And make sure you have imported the classes on route file.
as I saw, you're not sending data, so you can't say $class_id = Input::get('id');. You have id parameter in your url, just use it.
Route::get('ajax-group/{id}', function($class_id){
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
When the user changes the category with the select field, I want to only show the requests with that category on the view--and to do this using an AJAX request. I want to pass the object that is being returned from the Controller to AJAX's success handler into the view (the $requests variable as seen in the code below), and for the view to update the requests shown.
The data is being returned to AJAX's success handler correctly as I can console.log the object, but it doesn't update the $requests variable.
How do I achieve this, and what am I missing here?
The view that shows the requests from the DB
#extends('layouts.app')
#section('content')
{{-- Requests --}}
<div class="container">
<div class="row requests-row">
<div class="col-md-12">
<h2>New requests</h2>
<select name="category" class="form-control category">
<option value="" disabled selected>Choose a category...</option>
<option value="Electronics and Computers">Electronics and Computers</option>
<option value="Hardware">Hardware</option>
</select>
<hr>
<p class="block"></p>
#foreach ($requests as $request)
#include('components.requests')
#endforeach
</div>
</div>
</div>
#endsection
The AJAX Request
$('.category').change(function() {
$.ajax({
method: "GET",
url: "/category",
data: $(this).serialize(),
success: function(data) {
console.log(data);
return data;
},
error: function(data){
console.log("Error: " + data);
},
});
});
The controller on the backend that handles the AJAX request
public function changeCategory(Request $request)
{
$posts = Post::where('category', $request->category)->get();
return $posts;
}
Your template blade is php and ajax is from client side javascript.
So if you want to display something you need to use javascript to do it.
Maybe something like
success: function(data) {
var posts = '';
$.each(data, function(index, post) {
posts += '<div class="post">' + post.title + '</div>';
});
$('.requests-row .col-md-12').prepend(posts);
}
May be smth like that?
if($request->ajax()){
return response()->json(['ajax']);
}