How to get checkbox checked from database array using Laravel and Ajax - arrays

I'm trying to get data from database to checkboxes as checked. The checkbox data in database are as array that have been inserted with json and they are dynamic data based on insert function.
My tasks table:
id |employee_id | startDate | endDate | ...
---|------------|------------|-----------|--------
1 |["1","2"] | .......... | ..........| ....
My TasksController.php
function fetchdata(Request $request)
{
$id = $request->input('id');
$task = Task::find($id);
$output = array(
'employee_id' => $task->employee_id,
'name' => $task->name,
'description' => $task->description,
'startDate' => $task->startDate,
'endDate' => $task->endDate,
'percentage' => $task->percentage
);
echo json_encode($output);
}
public function getEmployeesList()
{
$employeesList = Employee::all();
return view('adminlte::tasks', ['employeesList' => $employeesList]);
}
My tasks.blade.php
#foreach($employeesList as $emplist)
<label class="checkbox-inline">
<input type="checkbox" id="employee_id" name="employee_id[]" class="chck" value="{{$emplist->id}}" >{{ $emplist->name }}</label>
#endforeach
My Ajax function inside blade:
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url: "{{route('tasks.fetchdata')}}",
method: 'get',
data: {id:id},
dataType: 'json',
success:function(data)
{
$('#id').val(data.id);
$('#employee_id').val(data.employee_id);
$('#name').val(data.name);
.......................
..................
}
})
});
So, how can I retrieve data from database to checkboxes as checked, because for now I'm getting null "employee_id" value when I try to update a record.
Thank you in advance

Since you're encoding the data on the server side, you must decode it in the client side like :
...
success:function(data)
{
console.log( data );
data = JSON.parse(data);
$('#id').val(data.id);
$('#employee_id').val(data.employee_id);
$('#name').val(data.name);
...
}

Related

Passing json from db to blade template

Let say I have ["gravy1", "gravy2"] in table's column "gravy". How can I display it so I can get this result:
This is my controller:
$grav = DB::table('items')
->select('gravy')
->get();
$gravies = json_decode($grav);
return view('welcome', [
'gravies' => $gravies,
]);

Insert array using codeigniter

I try to insert multiple arrays into database using codeigniter and ajax. After click the submit, database insert to mysql but all the value is blank. What did I miss?
My view:
<input type="hidden" name="iduser[]" id="iduser[]" value="<?php echo $rowmyuser->iduser; ?>"/>
<input type="hidden" name="idproduk[]" id="idproduk[]" value="<?php echo $rowproduk->idproduct; ?>"/>
<input type="text" class="form-control input-sm" name="settarget[]" id="settarget[]"/>
Save
My controller:
public function inserttarget()
{
$this->target_m->inserttarget_m();
}
My model:
function inserttarget_m() {
$iduser = $this->input->post("iduser");
$idproduk = $this->input->post("idproduk");
$settarget = $this->input->post("settarget");
$temp = count($this->input->post("iduser"));
$datatarget = array();
for($i=0; $i < 3; $i++)
{
$datatarget[]=array(
"iduser"=>$iduser[$i],
"idproduct"=>$idproduk[$i],
"target"=>$settarget[$i],
);
}
$this->db->insert_batch("tbl_targetsales",$datatarget);
}
The Ajax code:
function insert_target()
{
var DataString=$("#frm_target").serialize();
document.getElementById("save_target").innerHTML = "<i class='fa fa-cog fa-spin fa-lg fa-fw'></i> Saving...";
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>target/inserttarget',
data: DataString,
success: function (data) {
//jQuery("#attendence_report_holder").html(response);
swal({
text: 'success'
});
$("#frm_target")[0].reset();
document.getElementById("save_target").innerHTML = "<i class='fa fa-save'> </i>Save";
window.location='<?php echo base_url(); ?>target';
},
error:function(data){
swal({
text: 'error',
});
document.getElementById("save_target").innerHTML = "<i class='fa fa-save'> </i>Save";
}
});
}
I need advice please, what is the problem in the code. Thanks in advance
first you call wrong the inputs in your html for the inputs name are
iduser[]
idproduk[]
settarget[]
and in your model you call with, and in the array you make to insert you call different variables that you save it
iduser
idproduct
target
replace all you madel with (using the correct names from form and variables names)
function inserttarget_m() {
$iduser = $this->input->post("iduser");
$idproduct = $this->input->post("idproduk");
$target = $this->input->post("settarget");
$temp = count($iduser);
$datatarget = array();
for($i=0; $i < $temp; $i++){
$datatarget[] = array(
"iduser" => $iduser[$i],
"idproduct" => $idproduct[$i],
"target" => $target[$i],
);
}
$this->db->insert_batch("tbl_targetsales", $datatarget);
}

Yii2 - Bulk checkbox by GET request

I have a checkbox in a gridview Yii2 like this,
[
'class' => 'kartik\grid\CheckboxColumn',
'width' => '20px',
'checkboxOptions' => function ($model, $key, $index, $column) {
return [
'value' => trim($model->vessel),
];
}
],
Then to get all the value checkbox in yii2, I use this button
Html::a('<i class="glyphicon glyphicon-print"></i> Print All',
["print-all-based-date"],
[
"class" => "btn btn-success",
'role' => 'modal-remote-bulk',
])
But when in my controller that handle the the action,
public function actionPrintAllBasedTanggal()
{
$request = Yii::$app->request;
$get = $request->get();
print_r($get);
die();
I get :
Array
(
[r] => iwwi/incoming/print-all-based-tanggal
[KMTC_HOCHIMINH,OOCL_NAGOYA] =>
[_] => 1495123320863
)
What it means [KMTC_HOCHIMINH,OOCL_NAGOYA] =>,
I check in html, the checkbox is named selection[] ?
I need this : KMTC_HOCHIMINH,OOCL_NAGOYA
to get continue my app.
Please advise.
Thanks
may be you can use jquery for the solution.
example :
$(document).on('click','#ceklist_all',function(){
if ($(this).is(':checked')) {
$('.ceklist_child').attr('checked',true);
your_variable = [];
$('.ceklist_child:checked').map(function(key,val) {
if(this.checked) {
your_variable[key] = this.value;
}
}).get();
}
});
so,. you can use the your_variable and use the ajax for submit..
$.ajax({
type: 'get',
url: your_url,
data: {
'your_variabel_to_post' : your_variable
},
success: function(data){
// success function
},
error: function(data){
if(data.responseText)
alert(data.responseText);
},
});
CMIIW,.
just the optional solution. heheh

manipulate data fetched from remote api angular 2

Im receiving data from the Marvel api and use ngFor to display the data.
Before displaying the data I need to make some changes to it.
If the name doesn't exist or the description is empty I want to show a message.
Where is the best place to manipulate data and how can I do this?
I tried something like this in my comic view after the subscribe but it didnt work.
If (stuff.data.results['0'].title == ''){
stuff.data.results['0'].title == 'try gain'}
my service.ts
getComics(searchterm): Observable<any> {
const search: URLSearchParams = new URLSearchParams();
search.set('titleStartsWith',searchterm);
search.set('ts', '1'); // time stamp
search.set('apikey', 'key');
search.set('hash', 'key');
let obs: Observable<any> = this.http
.get(ComicService.BASE_URL, new RequestOptions({search}))
.map( (res) => res.json());
console.log("obj " + obs)
return obs;
}
my comic-view.ts
searchComics(event): boolean {
this.error = 'fout'
this._comicService.getComics(this.searchterm)
.subscribe(
stuff => {
this.stuff = stuff; console.log('title: ' + stuff.data.results['0'].title + ' description:' +
stuff.data.results['0'].description);
},
error => { this.error = error; }
);
return false;
}
comis.html
<ul>
<li *ngFor=" let x of stuff?.data?.results ">
<label> Title:</label> {{x.title}}
<br>
<label> description: </label> {{x.description}}
<br>
</li>
</ul>

telerik-mvc grid - how to format footer template?

This is my code in the controller:
[GridAction]
public ActionResult _Select()
{
// Creating dummy data to bind the grid
var data = Enumerable.Range(1, 100)
.Select(index => new Customer
{
ID = index,
Name = "Customer #" + index,
Tax = 1 + index,
Amount = 500 + index
});
return View(new GridModel(data));
}
This is what I have in my view:
<%: Html.Telerik().Grid<GridLoadedWithAjaxInTabStrip.Models.Customer>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.ID).Width(200);
columns.Bound(c => c.Name);
columns.Bound(c => c.Tax);
columns.Bound(p => p.Amount);
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Select", "Home"))
.Sortable()
.Pageable()
.Groupable()
.Filterable()
%>
I would like to know how I can put a custom footer template in this format:
Total Tax: XXXXX
Total Amount: XXXXX
Grand Total: XXXXXXX
Please assist me how I can do this. Thanks!
You need to check this demo
http://demos.telerik.com/aspnet-mvc/grid/aggregatesajax

Resources