Get Multiple Check Box Values to View Data From MYSQL in TWIG - php

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');

Related

Datatable sorting not working properly after destroyed the table and recreate

I using Jquery to clear the table tbody and reinsert in via ajax call. after the data is showed, but the sorting function is not working properly. here is my codes..
<table class="table table-bordered table-striped table-condensed flip-content table-hover" style="table-layout:fixed;" id="datatable1">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="agtBody">
<?php
foreach($results as $result) :
?>
<tr>
<?php if(isset($game_name['gpname'])){?>
<td><?=$game_name['gpname']?></td>
<?php }else{ ?>
<td><?=$result['gpid']?></td>
<?php } ?>
<td style="text-align:right;"><?=Helper::money($result['betAmt'])?></td>
<td style="text-align:right;"><?=Helper::money($result['payout'])?></td>
<td style="text-align:right;"><?=Helper::money($result['winLoss'])?></td>
<td style="text-align:right;"><?=Helper::money($result['validbetamount'])?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot id ="agtFoot">
<tr style="background-color:#FFEEDD;">
<td>Total</td>
<td style="text-align:right;"><?=Helper::money($totalbetAmt)?></td>
<td style="text-align:right;"><?=Helper::money($totalpayout)?></td>
<td style="text-align:right;"><?=Helper::money($totalwinLoss)?></td>
<td style="text-align:right;"><?=Helper::money($totalvalidbetamount)?></td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
function search_agtdetail(agentcode) {
if($("#agt_StartTime").val() == "" || $("#agt_EndTime").val() == "") {
alert("<?php echo 'Not Valid' ?>");
} else {
$("#agtBody").empty();
$("#agtFoot").empty();
$.ajax({
type: "post",
url: "/report/agentBoxAjax",
dataType: "json",
data: {
start_date: $("#agt_StartTime").val(),
end_date: $("#agt_EndTime").val(),
agent_code : agentcode,
},
success: function (data) {
$('#datatable1').dataTable().fnDestroy();
$('#agtBody').html(data.html);
$('#agtFoot').html(data.html_foot);
$('#datatable1').css('width', '');
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
}
});
}
}
$(document).ready(function(){
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
});
</script>
Can someone help me? The sorting is not working properly..
Its look like using the old data for sorting it.
i had less experience on jquery, someone please help. Thank you so much.
Extending on Bhushan Kawadkar comment you need to use the API method for this.Also you should be using the ajax methods for your datatable.
For example, lets say that i get the server side data from a script called data.php, i would just call it like this:
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
"ajax": {
"url": "data.php",
"type": "GET"
}
});
the post.php needs to return the data in json format like this (using car as example):
{
"data":[
[
"Ford",
"Fiesta",
"2015"
],
]
}
in your success section in the ajax call instead of destroying the table just use:
$('#datatable1').ajax.reload()
Here's a snippet just in case.
$(document).ready(function() {
var table = $('#example').DataTable({
"ajax": 'https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/arrays.txt',
});
$("#reload_table").on("click",function(){
console.log("reloading data");
table.ajax.reload();
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<html>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Profession</th>
<th>City</th>
<th>Date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</body>
<input id="reload_table" type="button" value="RELOAD TABLE">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
</html>

is there a way to delete my databse row using a button and php

I created a table with my PHP and database and added a delete button on the right of each of my element in my first column and I want this button to delete the row in my database but I don't know how to link my button to a PHP action
<table border="2" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col"><h6>Nom de l'Etape</h6></th>
<th scope="col"><h6>Description de l'Etape </h6> </th>
</tr>
</thead>
<?php
$req='SELECT * FROM Etape';
$resultat=$dbh->query($req);
while ($ligne=$resultat->fetch()) {
echo "<tr> <td>". $ligne[0]."<button type=\"button\" onclick=\"alert('Hello world!')\">delete</button></td><td>".$ligne[1]."</td> </tr>";
}
?>
</table>
The easiest way is to use ajax:
<?php
// Check if is background ajax query or user just enter page
// Is background ajax query, run PHP code
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'):
// RUN PHP CODE IN BACKGROUND (IN YOUR CASE: DELETE ROW FROM DB)
else:
// Is not ajax query - show HTML page
?>
<table border="2" class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col"><h6>Nom de l'Etape</h6></th>
<th scope="col"><h6>Description de l'Etape </h6> </th>
</tr>
</thead>
<?php
// Your PHP function to get button from database
$req='SELECT * FROM Etape';
$resultat=$dbh->query($req);
while ($ligne=$resultat->fetch()) {
echo '<tr> <td>'. $ligne[0].'<button type="button" value="<?php echo $ligne[0]; ?>">delete</button></td><td>'.$ligne[1].'</td></tr>';
}
?>
</table>
<!-- Load jQuery -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
// Button click
$(document).on('click','button',function(e) {
// Get button value
var my_id = $(this).val();
// Prepare ajax query
$.ajax({
type: "POST",
dataType:"json",
// Set url to file itself
url: window.location.href,
// set data
data: "id=" + my_id,
beforeSend: function (data) {
alert('Sending');
},
success: function (data)
{
alert('Success');
},
error: function (data)
{
alert('Error');
}
});
});
</script>
<?php endif; ?>

Datatable not working on ajax call

I use Datatable in my web application.
Following is my simple code to get data using ajax.
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
<body>
<h2>AJAX SELECT</h2><hr>
<div align="center">
Select Team :
<select name="select" id ='teamSelect'>
<option value="">Select Value</option>
<option value="op2">Company 1</option>
</select>
</div>
<div id='tableContainer' align="center"></div>
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
}
});
});
});
</script>
and Getdata.php Code
<table id="mytable" class="display" cellspacing="0" width="50%">
<thead>
<tr>
<th>First name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
</tr>
</tbody>
I Link Jquery, datatable css and js both.but still It return output as normal HTML table.
No console error founded.
I need that data in datatable. So how can i get that.
and i also tested datatable in index.php page. It working quite good.
You are initializing datatable before table added. You need to initialize it in ajax
remove following script
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
update ajax as below:
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
$('#mytable').DataTable({
"destroy": true, //use for reinitialize datatable
});
}
});
});
});
</script>
Put
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
At the bottom of your Getdata.php file also links to the datatable css and js.
Or use ajaxComplete function() to call the datatable.

AJAX & PHP: Display search result on DataTable of GET request from form submitting

I have form to search any person in database.
Then I want to display the search result in DataTable.
I am using blade for templating HTML.
This is my form:
<form id="myform" method="GET" action="{{ site_url('person/search') }}">
This is my DataTable section in my HTML
<section class="panel" style="margin-top:20px;">
#include(config_item('theme').'.person.part.table-person', compact('result'), ['id' => 'persons'])
</section>
This is my table:
<table id="{{ $id }}" data-toggle="table" data-mobile-responsive="true">
<thead>
<tr>
<th data-field="image" data-align="center">Image</th>
<th data-field="id" data-visible="false">ID</th>
</tr>
</thead>
</table>
And for the last is my AJAX code:
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
dataType: json,
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#persons').html(response);
}
});
return false;
});
});
With all that codes, I can't display the search result.
am I doing something wrong?
Thanks
make sure .. you cant duplicate same id name
use jQ append to display table detail
$('#channels').append(' <tr>
<th data-field="image" data-align="center">Image</th>
<th data-field="id" data-visible="false">ID</th>
</tr>');
HINT : http://api.jquery.com/append/

update data from database using <select onchange()><option> using laravel 5

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");
}
});
})

Categories