please help me. how i can update data from database using select option, ajax onchange without submit.
my view :
{!! Form::model($UserAccess,['method' => 'POST','url'=>['setting/updaterole']]) !!}
<table class="dataTable" id="table-user">
<thead class="grey lighten-3">
<tr>
<td class="center-align no-sort">Photo</td>
<td class="center-align">Fullname</td>
<td class="center-align">Rule</td>
<td class="center-align">Action</td>
</tr>
</thead>
<tbody>
<?php $hitung = $UserAccess->count(); ?>
#foreach($UserAccess as $list)
<tr>
<td class="center-align" width="50">
#if($list->avatar == NULL)
<img class="circle responsive-img" width="50" src="{{asset(config('param.url_uploads').'blank.jpg')}}"/>
#else
<img class="circle responsive-img" width="50" src="{{$list->avatar}}"/>
#endif
</td>
<td class="red1-text lato-bold center-align">{{$list->name}}</td>
<td class="center-align" width="150">
<select id="selectrole" name="selectrole" data-url="{{url('/setting/updaterole')}}" data-token="{{ csrf_token() }}">
#foreach($UserAccessRole as $listRole)
<option value="{{$listRole->id}}" #if($list->user_access_role_id_fk == $listRole->id) selected="selected"#endif>{{$listRole->name}}</option>
#endforeach
</select>
</td>
<input type = "hidden" value = "{{$list->id}}" name = "idmain">
#if($hitung > 2)
<td class="center-align">
<a href = "remove_access/{{$list->id}}/delete" >Remove Access<a/>
</td>
#else
<td class="center-align">Remove Access</td>
#endif
</tr>
#endforeach
</tbody>
</table>
{!! Form::close() !!}
#section('page-script')
<script type="text/javascript">
$('select').on('change',function(){
var city = $( "select option:selected" ).val();
var token = $(this).data('token');
var base_url = $(this).data('url');
$.ajax({
url:base_url+'/updaterole',
type: 'POST',
data: { _token :token,city_id:city_id },
success:function(msg){
alert("success");
}
});
})
</script>
#endsection
my controller :
public function doUpdateAccessRole($id, Request $request)
{
$place_id = $request->get('id');
$Role = UserAccess::findOrFail($id);
$Role->user_access_role_id_fk = $id_role;
$Role->update($request->all());
return 'success';
}
my routes
Route::post('setting/updaterole',['uses'=>'SettingController#doUpdateAccessRole','as'=>'updateaccessrole']);
i don't understand whats wrong with my code. when i change the select option value nothing happen with my program. please help me, thank you.
Try this
$('#selectrole').on('change',function(){
var city = $(this).val();
var token = $(this).data('token');
var base_url = $(this).data('url');
$.ajax({
url:base_url+'/updaterole',
type: 'POST',
data: { _token :token,city_id:city_id },
success:function(msg){
alert("success");
}
});
})
Related
I am a beginner at laravel,I have two form form1 which contains year and month and radio buttons of 1st and 2nd quanziane and selects of Salaries and chantiers and button when I click on button cherche for form1 to hide and form2 to display and also I get data according to the conditions of the form1 fields I use ajax this data I want to display it in form 2 table,for explain more I have Salaries working on Chantiers and who must point the day work every day, table Pointages contain id, Chantier_id foreign key of table Chantiers where they work, ouvrage_id (foreign key of table ouvrages) task gives to perform, datep date of Pointages, Sold price of Salaries for day, now I want to display in the table of balde payer.balde.php The total salaire of the worker who owes it to the company in which he works is per month or the 1st somaine of the month or the 2nd somaine of the month, depending on the client's choice, I could have data in the console but when I want to display it in my blade I get this error someone can resolve this error.
payer.balde.php
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>Anne</th>
<th>mois</th>
<th>matricule </th>
<th>prenom</th>
<th>salaire Net</th>
<th>sold</th>
<th>edit</th>
<th>delete</th>
<th>details</th>
</tr>
</thead>
<tbody>
#foreach($dataP as $salarie)
<tr id="{{$salarie->id}}">
<td><input type="checkbox" class="checkbox" name="customer_id[]" value="{{$salarie->id}}" /></td>
<td><input type="hidden" class='year' class="form-control" /></td>
<td><input type="hidden" class='month' class="form-control" /></td>
<td>{{ $salarie->id }} </td>
<td>{{ $salarie->nom }}</td>
<td>{{ $salarie->prenom }}</td>
<td>{{ $salarie->sold }}</td>
<td>Editer</td>
<form action="{{ url('salaries', ['id' => $salarie->id]) }}" method="post">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<td><button type="submit" class="btn btn-theme04 btn-sm" role="button">Delete</button></td>
</form>
<td>Show</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th></th>
<th>annee</th>
<th>mois</th>
<th>matricule </th>
<th>nom</th>
<th>prevom</th>
<th>sold</th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
<!------------->
</section>
</section>
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true)){
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);}
});
$("#form2").hide();
let now = new Date();
let year = now.getFullYear();
let month = ("0" + (now.getMonth() + 1)).slice(-2);
$('#annee').val(year);
$('#mois').val(month);
$("#hide").click(function(){
$("#form1").hide();
$("#form2").show();
let chan = $("#chantier_id option:selected").text();
$('#ch').text(chan);
let sal = $("#salarie_id option:selected").text();
$('#sa').text(sal);
let ann = $("#annee").val();
$('#an').text(ann);
let moi = $("#mois").val();
$('#mo').text(moi);
$('.year').text(ann);
let chan_id = $("#chantier_id option:selected").val();
let sal_id = $("#salarie_id option:selected").val();
$('.month').val(mois).parent().prepend(moi);
$('.year').val(ann).parent().prepend(ann);
var radioValue = $("input[name='quanzaime']:checked").val();
if(radioValue){
console.log(radioValue);
}
$.ajax({
type: 'get',
url: "{{ route('salarie.payerP') }}",
data: {
'quanzaime':radioValue,
'annee':ann,
'mois':moi,
'salarie_id':sal_id,
'chantier_id':chan_id
},
success: function(data1){
console.log(data1);
},
error: function(){
console.log('error');
},
});
});
});
</script>
SalarieController.php
public function payer(){
$pointages = Pointage::get();
$salaries = Salarie::get();
$chantiers = Chantier::get();
return view('salarie.payer', compact('salaries','pointages','chantiers'));
}
public function payerP(request $request){
if($request->quanzaime == 1){
$dataP = DB::table('salaries')
->join('pointages','pointages.salarie_id','salaries.id')
->selectRaw('SUM(pointages.sold) as sold,salaries.nom,salaries.prenom,salaries.id')
->whereRaw(DB::raw('YEAR(pointages.datep) = ' .$request->annee))
->whereRaw(DB::raw('MONTH(pointages.datep) = ' .$request->mois))
->whereRaw( DB::raw('DAY(pointages.datep)>0 AND DAY(pointages.datep)<16'))
->Orwhere('pointages.salarie_id','=',$request->salarie_id)->OrWhere('pointages.chantier_id','=',$request->chantier_id)
->groupBy('pointages.salarie_id')
->get();
return response()->json(['salarie'=>$dataP]);
}elseif($request->quanzaime == 2){
$dataP = DB::table('salaries')
->join('pointages','pointages.salarie_id','salaries.id')
->selectRaw('SUM(pointages.sold) as sold,salaries.nom,salaries.prenom,salaries.id')
->whereRaw(DB::raw('YEAR(pointages.datep) = ' .$request->annee))
->whereRaw(DB::raw('MONTH(pointages.datep) = ' .$request->mois))
->whereRaw( DB::raw('DAY(pointages.datep)>15 AND DAY(pointages.datep)<31'))
->Orwhere('pointages.salarie_id','=',$request->salarie_id)->OrWhere('pointages.chantier_id','=',$request->chantier_id)
->groupBy('pointages.salarie_id')
->get();
return response()->json(['salarie'=>$dataP]);
}else{
$dataP = DB::table('salaries')
->join('pointages','pointages.salarie_id','salaries.id')
->selectRaw('SUM(pointages.sold) as sold,salaries.nom,salaries.prenom,salaries.id')
->whereRaw(DB::raw('YEAR(pointages.datep) = ' .$request->annee))
->whereRaw(DB::raw('MONTH(pointages.datep) = ' .$request->mois))
->Orwhere('pointages.salarie_id','=',$request->salarie_id)->OrWhere('pointages.chantier_id','=',$request->chantier_id)
->groupBy('pointages.salarie_id')
->get();
return response()->json(['salarie'=>$dataP]);
}
//dd($request);
}
web.php
Route::get('/payer','SalarieController#payer');
Route::get('/payerP','SalarieController#payerP')->name('salarie.payerP');
I'm currently using Codeigniter and using Ajax to post my search result through the server and result the result and display on my responsive datatable. However the result was not added into my datatable and i even try to add it with .append but it just added below my table and the search function on datatable is not searching it and it still show "No data available in table".
Here are my View :
<div id="reporting" class="container">
<h3 class="section-title">Export Time Location Panel</h3>
<form id = "search">
<div class="form-group">
<div class="form-group">
<h5>Date/ Time</h5>
<input type="datetime-local" name="datetime" id = "datetime">
<?php echo form_error('datetime'); ?>
</div>
</div>
<button type="submit" class="btn btn-primary">Confirm</button>
</form><br/>
<table class="table table-bordered table-light" >
<thead>
<tr>
<td class="id">ID</td>
<td class="na">NA Name</td>
<td class="centre">Centre Name</td>
<td class="login">Date & Time</td>
<td class="lat">Latitude</td>
<td class="long">Longtitude</td>
<td class="accuracy">Accuracy</td>
<td class="place">Location Name</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<?php include('footer.php'); ?>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var tbl = $('.table').DataTable({
responsive: true,
"order": [[0, "desc"]]
})
$( "#search" ).submit(function(event) {
event.preventDefault();
var value = $("#datetime").val();
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>location/search_record',
data:{'datetime':value},
success:function(data){
$('.table').append(data);
}
});
});
} );
</script>
Here are my Model :
public function search_record(){ //Display Record at View Page
$this->load->model('location_model');
$this->load->library('form_validation');
echo '
<tr>
<td class="id">ID</td>
<td class="na">NA Name</td>
<td class="centre">Centre Name</td>
<td class="login">Date & Time</td>
<td class="lat">Latitude</td>
<td class="long">Longtitude</td>
<td class="accuracy">Accuracy</td>
<td class="place">Location Name</td>
</tr>
';
}
You have to add data to table body by
success:function(data){ tbl.rows.add($(data)).draw(); }
Please check this link
https://jsfiddle.net/kuLcqwav/3/
https://datatables.net/examples/api/add_row.html
This is my Controller:
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$deployments = $this->getDoctrine()
->getRepository('AppBundle:Billing')
->findAll();
return $this->render('default/index.html.twig', array('deployments' => $deployments));
}
/**
* #Route("/results", name="resultsPage")
*/
public function resultsAction(Request $request)
{
return $this->render('default/results.html.twig');
}
/**
* #Route("/route/action/save", name="route-action-save")
* #Method({"POST"})
*/
public function checkBoxAction(Request $request){
return $arrayTenantID = $request->request->get('allvals');
}
The snippet of code below is in my index.html.twig file
<form>
<div id="stuffTable">
<table class="table table-hover" action="" method="post"> <thead>
<script src="{{ asset('bundles/public/js/libs/jquery.min.js') }}"> </script>
<tr> <th>Tenant ID</th>
<th>Tenant</th>
</tr>
</thead>
<tbody>
{% for stuff in deployments %}
<tr>
<th scope="row">
<input type="checkbox" value="{{stuff.tenantID}}" id="tenantID">
<label for="tenantID">{{stuff.tenantID}}</label>
<td>{{stuff.tenantName}}</td>
</th>
</tr>
{% endfor %}
</tbody>
</div>
</table>
<textarea id="textArea"></textarea>
The table (image below) shows the TenantID and TenantName, but how do I use the checkbox so after clicking the "submit" button, another table will show data of the checked TenantIDs only?
To make my question a bit more clear,how do I save the TenantID values after they have been checked, so I can use it to Query the same table? I am using Doctrine to query.
<script>
function updateTextArea() {
var allVals = [];
$('#stuffTable :checked').each(function() {
allVals.push($(this).val());
});
$('#textArea').val(allVals);
sendData(allVals);
}
$(function() {
$('#stuffTable input').click(updateTextArea);
updateTextArea();
});
function sendData(allVals) {
$.ajax({
url: "{{ path('route-action-save') }}",
type: 'POST',
dataType: 'json',
data: {"allVals": allVals},
success: function(response){
alert("hello");
}
});
}
This is my JavaScript and it seems to give me an error:
http://localhost:8000/route/action/save 500 (Internal Server Error)
Thank you in advance.
Try this, you have the table with tenants Id:
<head>
<script src="jquery-2.2.4.min.js"></script>
</head>
<table class="table table-hover"> <thead>
<tr> <th>Tenant ID</th>
<th>Tenant</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">
<input type="checkbox" name="tenantNum[]" value="1000"> 1000</th>
<td>tenant_Name</td>
</tr>
<tr>
<th scope="row">
<input type="checkbox" name="tenantNum[]" value="1001"> 1001</th>
<td>tenant_Name</td>
</tr>
<tr>
<th scope="row">
<input type="checkbox" name="tenantNum[]" value="1002"> 1002</th>
<td>tenant_Name</td>
</tr>
</tbody>
</table>
<button type="button" id="tenant_id_button" >Ok</button>
Now, You could use Jquery and get multiple checkboxes values (checkboxes that you have been clicked) and after that, send it to php file (process_tenant.php)
<script>
$(document).ready(function () {
$('#tenant_id_button').click(function () {
//Get checked Id
var array_tenant_id = new Array();
$("input:checked").each(function () {
array_tenant_id.push($(this).val());
});
//array_tenant_id = ["1000", "1002"]
$.ajax({
url: "process_tenant.php",
method: 'POST',
dataType: 'json',
data: {"array_tenant_id": array_tenant_id},
success: function (data) {
//read response: data
}
});
});
});
</script>
Now, you will get the checkboxes values server-side (file process_tenant.php)
<?php
$array_tenant_id = $_POST['array_tenant_id'];
var_dump($array_tenant_id);
The output will be an array with checkboxes previously checked:
array(2) (
[0] => (string) 1000
[1] => (string) 1002
)
** If you use Symfony **
Include Jquery library where you have the html table or include it in your base.html.twig
<script src="{{ asset('bundles/public/js/libs/jquery.min.js') }}"> </script>
Now, send 'array_tenant_id' as parameter to your controller:
$.ajax({
url: "{{ path('route-action-save') }}",
method: 'POST',
dataType: 'json',
data: {"array_tenant_id": array_tenant_id},
In the controller:
/**
* #Route("/route/action/save", name="route-action-save")
* #Method({"POST"})
*/
public function saveSomething(Request $request) {
$array_tenant_id= $request->request->get('array_tenant_id');
when i load the page normally everything is going, the form is submitted and i get the right responses .. but when i load the page with .load() function jQuery the form doesnt submitted! and i get nothing from Ajax function!! any help
this is my HTML :
<div class="container">
<div class="row">
<h4>Manage Contents</h4>
<div class="table-responsive table3">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Content</th>
<th>Owner</th>
<th>Created Date</th>
<th>Project</th>
<th>Priorty</th>
<th>Options</th>
</tr>
</thead>
<tbody>
#if ($availabe >= 1 )
<?php $i =1; ?>
#foreach ($avashown as $key)
<?php //this is edit content form?>
#if(isset($index) && $index == $i && isset($editid) && isset($idexist) && $idexist == $key->id)
<tr>
<form id="edit-content-form" action="/testajax" method="POST">
<td>{{ $i }}</td>
<td hidden="hidden">{{ csrf_field() }}</td>
<td hidden="hidden"><input type="hidden" name="id" value="{{ $editid }}"></td>
<td hidden="hidden"><input type="hidden" name="index" value="{{ $index }}"></td>
<td colspan="3">
<div class="control-group" id="inputField1">
<input class="form-control" type="text" name="content" value="{{ $key->content }}">
<span class="help-block hideme" id="help-block1"></span>
</div>
</td>
<td colspan="1">
<div class="control-group" id="inputField2">
<select class="form-control" name="project">
#foreach ($projects as $project)
<option value="{{ $project->id }}">{{ $project->projectname }}</option>
#endforeach
</select>
<span class="help-block hideme" id="help-block2"></span>
</div>
</td>
<td colspan="1">
<div class="control-group" id="inputField3">
<select class="form-control" name="priority">
#foreach ($priorities as $priority)
<option value="{{ $priority->id }}">{{ $priority->value }}</option>
#endforeach
</select>
<span class="help-block hideme" id="help-block3"></span>
</div>
</td>
<td>
<input type="submit" id="submitForm" name="submit" value="Done">
</td>
</form>
</tr>
<?php $i++;//i have to increase it here again?>
#else
<tr>
<td class="hidden"></td>
<td>{{ $i }}</td>
<td>{{ $key->content }}</td>
<?php $firstname = \App\User::find($key->owner_id);?>
<td>{{ ucfirst($firstname->firstname) }}</td>
<td>{{ $key->created_at }}</td>
<?php $projectname = \App\Project::find($key->project_id);?>
<td>{{ $projectname-> projectname }}</td>
<?php $priorty = \App\Priority::find($key->priority_id);?>
<td><span class ="label label-{{ $priorty->name }}">{{ $priorty->value }}<span></td>
<td>
<span class="glyphicon glyphicon-trash" data-toggle="tooltip" data-placement="bottom" title="Delete" onclick="ContentStatus('delete/ajax/{{ $key->id }}')"></span><span> </span>
<span id="editContentGlyph" data-toggle="tooltip" data-placement="bottom" title="Edit" class="glyphicon glyphicon-cog" onclick="editContent({{ $i }},{{ $key->id }})"></span>
</td>
<?php $i++; ?>
</tr>
#endif
#endforeach
#else
<tr>
<td>0</td>
<td colspan="6">Let's Work and Add some Contents! Create</td>
</tr>
#endif
</tbody>
</table>
</div>
</div>
</div>`
this is my script file :
function editContent(index,id){
var place = ".table3 tbody tr:nth-child("+index+") " ;
var place = "#alltables" ;
var des = place+" > *";
$(document).ready(function(){
$( place ).load("http://localhost:8000/manage_contents/"+index+"/"+id+" "+des, function(){
});
});
}
$(document).ready(function(){
$(function(){
$('#edit-content-form').on('submit',function(e){
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
e.preventDefault(e);
$.ajax({
type:"PUT",
url:'http://localhost:8000/testajax',
data:$(this).serialize(),
dataType: 'json',
success: function(data){
$("#alerts").html(data.responseText);
if (data.updated) {
var place = ".table3 tbody tr:nth-child("+data.index+") " ;
var des = place+" > *";
$( place ).load("http://localhost:8000/manage_contents/ "+des, function(){
});
}
},
error: function(data,xhr, ajaxOptions, thrownError){
$.each(data.responseJSON, function(){
var i = 1;
$.each(this, function(index,error) {
$("#inputField"+i).addClass(" has-error");
$("#help-block"+i).removeClass(" hideme");
$("#help-block"+i).html("<strong>"+error+"</strong>");
i++;
});
});
},
})
});
});
});
`
I suspect its happening due to your HTML form is getting loaded via ajax and before that only your $(document).ready( code is getting executed. Hence at that time there will be no element with id edit-content-form present in DOM. So to deal with this situation try using event delegation technique like below:
$(function(){
$(document).on('submit','#edit-content-form',function(e){
// your existing code goes here
});
});
We are attaching the event listener to the document object which will be there for sure and then delegating to #edit-content-form whenever event occurs.
im having problems with an ajax request. the function is to increment/decrement items in a shopping cart. When the increment event is fire the post array comes up empty when printed.
Firebug shows the params being sent in the post request but in the controller nothing arrives.
The solution implemented is a bit scruffy but this is the way it has to be. The jquery is a non anonymous method outside the document.ready signature which could well be a contributor to the issue.
here's what I have...
jQuery
function increment_item($ciid){
$("#processing").fadeIn("fast");
$.ajax({
url: "<?=BASE_URL?>landing/inc_cart_item",
type: "post",
dataType: "json",
data: {id:$ciid,},
success: function(data){
$("#processing").fadeOut("fast");
if(data.error) {
alert(data.error);
} else {
// parent.$('#line1').text(data.line1);
//parent.$('#line2').text(data.line2);
//parent.$('#address-dialog').dialog('close');
alert(data.line1);
}
}
});
//return false;
};
The trigger in the view...
<a href="#" onClick="increment_item(<?=$item['cart_item_id']?>)" class="qty-inc-button" >More</a>
The controller method...
function inc_cart_item(){
$return_val = $this->cart_model->increment_cart_item($this->session->userdata('cart_id'),$this->input->post('id'));
}
EDITED TO ADD GENERATED SOURCE...
The table data
</thead>
<tbody id="item_2823">
<tr>
<td>
<img src="http://localhost/cdn/images/112/7/thumb_lemberger2010.jpg">
<p style="color: #666;">Bader</p>
<p style="font-size: 16px;">Stettener Lindhälder Lemberger</p>
Remove this item
</td>
<td class="align-td-center">
8.20€ </td>
<td class="align-td-center">
More
1 Less
<input id="item_id" class="item_id" value="2823" type="hidden">
</td>
<td class="align-td-center">
<span id="value-shipping-2823">8.20€</span>
</td>
</tr>
</tbody>
<tbody id="item_2824">
<tr>
<td>
<img src="http://localhost/***/cdn/images/112/5/thumb_kerfttropfle2010.jpg">
<p style="color: #666;">Bader</p>
<p style="font-size: 16px;">Kerftströpfle</p>
Remove this item
</td>
<td class="align-td-center">
5.10€ </td>
<td class="align-td-center">
More
1 Less
<input id="item_id" class="item_id" value="2824" type="hidden">
</td>
<td class="align-td-center">
<span id="value-shipping-2824">5.10€</span>
</td>
</tr>
</tbody>
Generated jquery
function increment_item($ciid){
$("#processing").fadeIn("fast");
$.ajax({
url: "http://localhost/***/***/landing/inc_cart_item",
type: "POST",
dataType: "json",
data: {id:$ciid},
success: function(data){
$("#processing").fadeOut("fast");
if(data.error) {
alert(data.error);
} else {
// parent.$('#line1').text(data.line1);
//parent.$('#line2').text(data.line2);
//parent.$('#address-dialog').dialog('close');
alert(data.line1);
}
}
});
};
Again the jQuery function im trying to use here is outside all the other generated jQuery in the $(document).ready(function() { code block, i dont know if this could be the cause.
I've been wrestling with it a little while now, all help is appreciated.
Thanks
Are you sure the data is being posted correctly? You have a comma inside your data json.
Also you could try:
data: JSON.stringify({id:$ciid})