Retrieve Data from Database to Option Value via AJAX - php

I am having problems trying to fetch some data from my database to display it in a value, I'm using Smarty as a template engine, I have my working code which is:
<div style="width: 50%">
<table id="listado" width="100%" cellpadding="2" cellspacing="1" border="0">
<thead>
<tr>
<th> </th>
<th style="text-align: center;">ID</th>
<th style="text-align: center;">NOMBRE</th>
<th style="text-align: center;">DOCUMENTO</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
{literal}
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": API_PATH+"/empresas/",
"method": "GET",
"dataType": 'json',
'cache':false
}).done(function (response) {
var allregs = [];
$.each(response, function(key,val){
var items = [];
items.push('<tr>');
items.push('<td style="text-align: center;">seleccionar</td>');
items.push('<td style="text-align: center;">'+val.id+'</td>');
items.push('<td style="text-align: center;">'+val.nombre+'</td>');
items.push('<td style="text-align: center;">'+val.documento+'</td>');
items.push('</tr>');
allregs.push(items);
});
$('#listado tbody').append(allregs.join(''));
}).fail(function(jqXHR, textStatus){
if(jqXHR.status == 404){
alert("No existen registros");
}
});
$('body').on('click','.selectEmpresa',function(){
var empresaid = $(this).attr('data-id');
$.ajax({
"url": API_PATH+"/empresas/select/"+empresaid,
"method": "GET",
"dataType": 'json',
'cache':false
}).done(function (response) {
location.href = SERVER_PATH+'/';
}).fail(function(jqXHR, textStatus){
alert('error');
});
});
});
</script>
{/literal}
it works perfectly using normal thead, tbody, tr, td, what im trying to do is fetch the same data just val.nombre but inside :
<div class="container">
<section>
<select class="cs-select cs-skin-border">
<option value="" disabled selected>Seleccionar Empresa</option>
<option value="prueba1">Prueba 1</option>
<option value="prueba2">Prueba 2</option>
<option value="prueba3">Prueba 3</option>
</select>
</section>
</div>
<script src="{$smarty.const.ASSETS_FOLDER}/select-empresas/classie.js"></script>
<script src="{$smarty.const.ASSETS_FOLDER}/select-empresas/selectFx.js"></script>
<script>
(function() {
[].slice.call( document.querySelectorAll( 'select.cs-select' ) ).forEach( function(el) {
new SelectFx(el);
} );
})();
</script>
instead of setting the values manually I want to fetch it from the database dynamically

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.

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

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

PHP script runs automatically on page load

need a favor. I wanted to make the internal PHP script runs automatically on page load. I have problems related to passing the value of the Date and User input from the form to the internal PHP script. I have tried both $_POST and $_GET. Should I put the script in an external script? I dont really need codes, just tell me what should I look into. Thanks!
Entry Log/Edit
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" type="text/javascript" src="js/simpledtpicker.js"></script>
</head>
<body style="text-align:center;">
<div class="wrapper">
<?php include('includes/header.php')?>
<h1 style="text-align:center;">Entry Log/Edit</h1>
<span>
<form action="#" method="GET">
<table style="width:100%;">
<tr>
<th style="text-align:left;">
Entries for:
<input type="text" name="dateOfEntry" class="dateOfEntry">
<script type="text/javascript">
$(function()
{
$('*[name=dateOfEntry]').appendDtpicker(
{
"dateOnly": true,
"dateFormat": "MM/DD/YYYY",
"autodateOnStart": true,
"closeOnSelected": true
});
});
</script>
</th>
<th style="text-align:right; padding-right: 0px;">
User:
<input type="text" name="user" value="Hrobi7198228" readonly="readonly" style="border:none; background-color:transparent"/>
</th>
<th width="5px;"><input type="submit" name="submit" value="Go"></th>
</tr>
</table>
</form>
</span>
<br>
<table class="entry" style="width: 100%;">
<thead>
<?php
include ('connServer.php');
$date = date('Y-m-d', strtotime(str_replace("-","/",$_GET['dateOfEntry'])));
$username = $_GET['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
if ($conn)
{
echo '<tr>
<th width="5px">Edit</th>
<th width="5px">Delete</th>
<th>Date</th>
<th>Details</th>
<th width="100px" style="text-align:center;">Downtime Type</th>
<th width="20px" style="text-align:center;">Machine No.</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px">Edit</td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td width="5px" style="text-align: center; padding: 0px 5px;">'.$row['Date'].'</td>';
echo '<td style="text-align: left; padding: 0px 0px 0px 12px;">'.$row['Description'].'</td>';
echo '<td style="text-align: center;">'.$row['TypeOfDowntime'].'</td>';
echo '<td style="text-align: center;">'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax
({
type: 'POST',
data: {'run':run},
success: function(data)
{
}
});
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id' : del_id},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
</script>
</tbody>
</table>
</div>
</body>
</html>
I am still progressing on it, but please help me find the correct terms to Google. I am fairly new to PHP and AJAX.
You can write below code in a js file and include the js file in your page.
$(document).ready(function(){
$.ajax({ url: "file.php",
data: data1,
success: function(){
// Do whatever you want to do here.
}});
});

Categories