Select default value in dropdown Ajax - ajax

i am trying to set default values in select.
Ajax:
$.ajax({
type: "GET",
url: "teachers/" + $(this).attr("value") + "/edit",
dataType: 'json',
success: function (data) {
$('.qual_id option[value=' + data.qualifs + ']').attr('selected', true);
}
Controller:
public function edit($id)
{
$qualifs = DB::table('qualif_teachers')
->join ('qualifs','qualif_teachers.qualif_id','=','qualifs.id')
->where('teacher_id', '=' , $id)
->pluck('qualifs.id');
return response()->json([
'status' => 'success',
'qualifs'=> $qualifs,
]);
}
View:
<select class="form-control qual_id">
<option value="">-Select Degree-</option>
<option value="1">SSC</option>
<option value="2">HSC</option>
<option value="3">BBA</option>
<option value="4">MBA</option>
</select>
Error:
Syntax error, unrecognized expression: .qual_id option[value=1,2]

Without being specific about the javascript framework you're using and without knowing the format of your ajax response, this works (assuming that defaultValue holds your desired option value):
var defaultValue = 1
$(`.qual_id option[value=${defaultValue}]`).attr('selected', true);
Here's a working fiddle.

Related

Laravel Controller/Ajax not saving in my database

It seems like my save(); in my categories does not function as intended below. I will show the necessary codes first:
my table name is hms_bbr_category which is also connectec to my .env locally:
DB_CONNECTION=pgsql
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=jhs
DB_USERNAME=postgres
DB_PASSWORD=pa55wor0
my model: HmsBbrCategory
class HmsBbrCategory extends Model
{
protected $table = 'hms_bbr_category';
protected $fillable = [
"category_name", "category_description"
];
}
my controller: BBRCategoryConfigurationController
class BBRCategoryConfigurationController extends Controller
{
public function index(){
return view('frontend.bbr-settings.bbr-category-configuration');
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails())
{
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
}
else {
$category = new HmsBbrCategory;
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->save();
return response()->json([
'status'=>200,
'message'=>'Category Added!',
]);
}
}
The ajax and modal fields
<div class="form-group">
<input type="text" class="form-control form-group w-100 category_name" placeholder="Category Name">
</div>
<div class="form-group">
<textarea class="form-control w-100 category_description" placeholder="Category Description" cols="50" rows="10"></textarea>
</div>
<script>
$(document).ready(function (){
$(document).on('click', '.add_category', function(e){
e.preventDefault();
var category_data = {
'category_name': $('.category_name').val(),
'category_description': $('.category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(category_data);
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: "category_data",
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400)
{
$('#saveform_errList').html("");
$('#saveform_errList').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#saveform_errList').append('<li>'+err_values+'</li>');
});
}
else
{
$('#saveform_errList').html("");
$('#success_message').addClass('alert alert-success');
$('#success_message').text(response.message);
$.('#createCategory').modal('hide');
$.('#createCategory').find('input').val("");
console.log(category_data);
}
}
});
});
});
</script>
my routes at web.php
Route::get('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'index']);
Route::post('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'store']);
Things to note:
my hunch is that my store function does not connect properly at $category = new HmsBbrCategory; However I have checked that my table name and the fields taken are the same, as seen at $category->category_name = $request->input('category_name');
I have also tested in ajax with the values by simply adding console.log(response) as seen in the screenshot, I cannot get past my validator to get to the save(). I am not sure how but There should not be an error since my text fields are filled.
I can elaborate more if needed, I am asking what can I change to fix my validation/save. thanks for any help.
As the error shows, The validation is failing (empty value i guess) and returning the code you programmed (400).
i'm guessing it is because you are using a string instead of the variable at the attribute data: "category_data",
update the code to send the variable instead
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data, //change here
dataType: "json",
success: function (response){
//...

Laravel ajax is not returning success data

I am trying to achieve a functionality, If I select a category in dropdown, then in next dropdown, subcategory of that chooces category will appear. I wrote below ajax in script tag for it.
$("#category").change(function(e){
e.preventDefault();
var category = $("#category").val();
$.ajax({
type:'POST',
url:"{{ route('ajaxRequest.post') }}",
data:{category:category},
success:function(data){
alert(data.success);
$("#subcategory").replaceWith(data.subcats);
}
});
});
Here is my route setup for the same
Route::get('add_product', [dashboardController:: class, 'addProduct']);
Route::post('add_product', [dashboardController::class, 'getSubCategories'])->name('ajaxRequest.post');
This is my controller function
function getSubCategories(Request $request){
//$input = $request->all();
$subCategoryList = DB::table('ajax_categories')->where('pid', $request->post('category'))->get();
$sub = '<option desabled selected>Choose sub category</option>';
foreach($subCategoryList as $subCategory):
$sub .= '<option value="'.$subCategory->id.'">'.$subCategory->category.'</option>';
endforeach;
return response()->json(array(
'success' => 'Success',
'subcats' => $sub
));
}
Everything seems fine, I am not getting what causing it to be fail.
Screenshot of network tab
On clicking on checkbox, I got this in reponse
You are echoing result before returning response so ajax is not able to parse json properly.And other is csrf token not passed properly.
In ajax you can pass csrf token like below
data:{_token: "{{ csrf_token() }}",category:category},
instead of appending in controller better do like this
function getSubCategories(Request $request){
$subCategoryList = DB::table('ajax_categories')->where('pid', $request->post('category'))->get();
$view=(string)view('dropdown',['subCategoryList'=>$subCategoryList])
return response()->json(array(
'success' => 'Success',
'subcats' =>$view
));
}
in your view dropdown.blade.php you can
#if(isset($subCategoryList)&&count((array)$subCategoryList))
#foreach($subCategoryList as $key=>$value)
<option value="{{$subCategory->id}}">{{$subCategory->category}}</option>
#endforeach
#endif

Why the if condition does not filtering the results?

I want to create advance search filtering staff data according to certain criteria chosed by users. This application developed using laravel 5. I am querying the data using ajax function and if statement to filter the criteria. The results appear but it does not filter any condition in the if statement.
The controller of the filtering condition is this:
public function kakitangan(Request $request)
{
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if ($request->section != ""){
$query->where('SectionID', $request->section);
}
$newitem = $query->get();
return response::json($newitem);
}
I also have tried this:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('section')) {
$query->where('SectionID', request('section'));
}
$newitem = $query->get();
return response::json($newitem);
But the result is the same..all data in itemregistrations appear in the output page. Although I select another section criteria.
This is the view page code for selection:
<div class="row">
<div class="col-lg-2">
{{ Form::label('Seksyen', 'Seksyen') }}
</div>
<div class="col-lg-2">
{{ Form::select('section', $sections, '', ['class' => 'form-control select2', 'placeholder' => '--pilih--']) }}
</div>
</div>
</div>
The selection id is from controller function:
$sections = Section::pluck('sectionname', 'SectionID');
//sent to html view
return view('carian.index', compact('sections'));
Button to call ajax function to get the query:
<button class="btn btn-primary btn-md" id="cari">Cari</button>
The code for results appear:
<script type="text/javascript">
$( "#cari" ).click(function() {
var seksyen = $("#section").val();
$.ajax({
url: '{{ url('kakitangan') }}',
data: {'section': seksyen},
dataType: 'json',
success: function (data) {
console.log(data);
$('#datatable tr').not(':first').not(':last').remove();
var html = '';
for(var i = 0; i < data.length; i++){
html += '<tr>'+
'<td>' + data[i].name + '</td>' +
'</tr>';
}
$('#datatable tr').first().after(html);
},
error: function (data) {
}
});
});
</script>
Should be when the user select a section, only staffs of the section appear. But now all staffs appear when select any section.
I just tried to test whether the section value is correctly passed to the controller using this in controller:
$try=$request->input('section');
return response::json($try);
It results empty array..no value passed? Is it the section value is not passed correctly? How to correct this problem?
You are passing the section as a post param while you performing a GET request.
Using jQuery you can send this as a query string using:
var seksyen = $("#section").val();
$.ajax({
url: '{{ url('kakitangan') }}?' + $.param({'section': seksyen}),
dataType: 'json',
...
In your controller you can also explicitly check if a request contains a query string using the has method on a request
if(request()->has('section')) {
$query->where('SectionID', request('section'));
}
EDIT:
using the laravel collective Form helpers you can specific the field id using the following (note the fourth argument id)
{{ Form::select('section', $sections, '', ['id' => 'section', 'class' => 'form-control select2', 'placeholder' => '--pilih--']) }}

display a json response

I have this json when sending json post request and fetching the return data
$.post("/employees", {id:"3"}, function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
console.log(response.employees);
$.each(response.employees, function(user_no, firstname, lastname){
$('<option/>', {
value:user_no,
text: firstname + " " + lastname
}).appendTo(branchName);
});
}
}, 'json');
and in my controller, it gets the id and find record/records where $branch_no is equal to $id and get the column user_no, firstname and lastname and return those as a json response.
public function getemployee(){
$id = $_POST['id'];
$employees = mot_users::where("branch_no", $id)
->select(array('user_no', 'lastname', 'firstname'))
->get()->toArray();
return response()->json(['success' => true, 'employees' => $employees]);
}
now it supposed to display the response as
<select>
<option value="1">Firstname Lastname</option>
<option value="2">Firstname Lastname</option>
<option value="3">Firstname Lastname</option>
<option value="4">Firstname Lastname</option>
</select>
but it display as
<select>
<option value="0">[object object]</option>
<option value="1">[object object]</option>
<option value="2">[object object]</option>
<option value="3">[object object]</option>
</select>
i got no error in my console and I think i fetch the json response incorrectly so any ideas, help, clues, suggestions, recommendations to make this work?
Try this
$.post("/employees", {id:"3"}, function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
console.log(response.employees);
$.each(response.employees, function(index, value){
$('<option/>', {
value:user_no,
text: value.firstname + " " + value.lastname
}).appendTo(branchName);
});
}
}, 'json');

How can I refresh a select list with another

I am trying hard to refresh a list after selecting an option of a second.
I have this list
<select id="ArticleShopId">
<option>Some options</option>
<option>Some options 2</option>
<option>Some options 3</option>
</select>
I have a seond
<select id="ArticleCategoryId">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
When I select an option of the first, ajax should load the table Shop and update the second select
I create an action called admin_refreshCategoriesAjax
function admin_refreshCategoriesAjax($id = null){
$this->loadModel('Category');
// Le list recupere la valeur des IDs et cherche un champs qui a la valeur "name"
$categories = $this->Category->find('list',array('order'=>'name ASC','conditions'=>array('shop_id'=>$id)));
//return "toto";
return $categories;
#return json_encode($categories);
}
I wish t create a ajax code to do it. Then I try doing it
$('select#ArticleShopId').on('change',function(){
//alert($(this).val());
//alert("/articles/refreshCategoriesAjax/"+$(this).val());
$.ajax({
type: "GET",
url: "<?php echo $this->Html->url(array('controller' => 'articles', 'action' => 'refreshCategoriesAjax', 'admin' => true)); ?>",
data: "id="+$(this).val(),
success: function(msg){
console.log(msg);
}
})
})
but msg does not return my an array with the $categories values.
How can I correctely call my action admin_refreshCategoriesAjax and update my second select with the value of $categories?
many thank for your help, I spend half day on it :o(
Note:
If I enter this in my URL
http://localhost:8888/web/admin/articles/refreshCategoriesAjax/1
it return me well the array I looking for. If I changer 1 with 2, it return my other value. Then this part seams to work nice
I believe your problem is that in your function admin_refreshCategoriesAjax you are returning the array rather than doing something that will actually output it to the webpage. You could do echo json_encode($categories); to get some output you can use without explicitly creating a view for that action.
Instead of finding an id in the parameter, you will find an id in $this->request->data. To make your ajax request secure, use the following code into your view file:
$('select#ArticleShopId').on('change',function(){
//alert($(this).val());
//alert("/articles/refreshCategoriesAjax/"+$(this).val());
$.ajax({
type: "POST",
url: "<?php echo $this->Html->url(array('controller' => 'articles', 'action' => 'refreshCategoriesAjax', 'admin' => true)); ?>",
data: {id:$(this).val()},
success: function(msg){
console.log(msg);
}
});
});
And the following code into your controller:
function admin_refreshCategoriesAjax(){
$categories = array();
if($this->request->is('post'))
{
$id = $this->request->data['id'];
$this->loadModel('Category');
// Le list recupere la valeur des IDs et cherche un champs qui a la valeur "name"
$categories = $this->Category->find('list',array('order'=>'name ASC','conditions'=>array('shop_id'=>$id)));
//return "toto";
}
return $categories;
#return json_encode($categories);
}
Now to fill the data in dropdown, return json_encode($categories) from your controller. And use var result = $.parseJSON(msg); in your ajax success method.

Resources