in the view file "(V_tampil_rekomendasi)", I made an input text containing the latitude and longitude values of a function to check the current location.
In the results, I sent it to the file controller and it worked. I checked using the var_dump function.
But when I send it (latitude and longitude) to the model file (M_Metode).The values of latitude and longitude were missing.
And the results that will be displayed on V_display_ recommendation are missing or nothing to display.
This my view file :
<button class="btn btn-primary" onclick="getLocation()">Cek Lokasi Anda</button></p>
<form action="<?php echo base_url().'metode/index'; ?>" method="post">
<div class="row">
<div class="col">
<p class="font-weight-bold">LATITUDE :</p>
<input class="form-control" type = "text" id = "out_latitude" name="latitude_awal" placeholder="Latitude" readonly/>
</div>
<div class="col">
<p class="font-weight-bold">LONGITUDE :</p>
<input class="form-control" type = "text" id = "out_longitude" name="longitude_awal" placeholder="Longitude" readonly/>
</div>
</div>
<br>
<input class="btn btn-primary" type="submit" value="Cari Fotografer">
</form>
<table class="table table-bordered" style="margin:20px auto;" border="1">
<tr>
<thead class="thead-dark">
<th>No</th>
<th>Nama</th>
<th>Alamat</th>
<th>Kamera</th>
<th>Spesifikasi Foto</th>
<th>Jarak</th>
</thead>
</tr>
<?php
$no = 1;
foreach($tb_fotografer as $fg)
{
?>
<tr>
<td><?php echo $no++ ?></td>
<td><?php echo $fg['nama'] ?></td>
<td><?php echo $fg['alamat'] ?></td>
<td><?php echo $fg['kamera'] ?></td>
<td><?php echo $fg['keahlian_foto'] ?></td>
<td><?php echo $fg['distance']?> Km </td>
</tr>
<?php } ?>
</table>
My Javascript to check the current location (in View file) :
<script>
var view_lat = document.getElementById("tampilkan_lat");
var view_long = document.getElementById("tampilkan_long");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
view.innerHTML = "Yah browsernya ngga support Geolocation bro!";
}
}
function showPosition(position) {
var var_latitude = position.coords.latitude;
document.getElementById("out_latitude").value = var_latitude ;
var var_longitude = position.coords.longitude;
document.getElementById("out_longitude").value = var_longitude ;
}
</script>
This my Controller :
function index()
{
$latitude = $this->input->post('latitude_awal');
$longitude = $this->input->post('longitude_awal');
$data_latlong = array(
'latitude_awal' => $latitude,
'longitude_awal' => $longitude);
$data_fotografer= $this->m_metode->tampil_data_fotografer($data_latlong);
$this->load->view('public/pencari/v_tampil_rekomendasi',['tb_fotografer' => $data_fotografer]);
}
This my model :
function tampil_data_fotografer($data_latlong)
{
$latFrom = deg2rad((float)('latitude_awal'));
var_dump($latFrom);
$lonFrom = deg2rad((float)('longitude_awal'));
var_dump($lonFrom);
$data_fg = $this->db->query("SELECT fotografer_id, nama, alamat, kamera, keahlian_foto, latitude, longitude FROM tb_fotografer");
$out = [];
{
foreach($data_fg->result_array() as $row)
{
$keahlianfoto = $row['keahlian_foto'];
$latTo = deg2rad((float)$row['latitude']);
$lonTo = deg2rad((float)$row['longitude']);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$distance = (2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latTo) * cos($latFrom) * pow(sin($lonDelta / 2), 2)))) * 6371;
if ($distance <=1)
{
$out[] = array_merge($row, ['distance' => $distance]);
}
}
}
return $out;
}
Anyone kno what the problem ? Help me please, thanks
The following code (in your model):
$latFrom = deg2rad((float)('latitude_awal')); // (float)('latitude_awal') = 0
var_dump($latFrom);
$lonFrom = deg2rad((float)('longitude_awal')); // (float)('longitude_awal') = 0
var_dump($lonFrom);
should be like this:
$latFrom = deg2rad((float) $data_latlong['latitude_awal']);
$lonFrom = deg2rad((float) $data_latlong['longitude_awal']);
Related
I found an error with my coding.
I here want to display data in DataTables with ajax. For the filter itself, it is dynamic so that the filter can be more than 1 depending on what is made. But when I want to display the data, there is an error which I don't know which side is the error. Here's the script:
By the way, im using CodeIgniter 3
View
<section class="content-header">
<div class="row" style="margin-left:15px; margin-right:15px; margin-bottom: 15px; ">
<div style="background-color: #E9fbf0; background-repeat:no-repeat; background-size:contain; background-position:center; padding: 30 0 0 10; border-radius: 15px; border:1px solid black;">
<div class="col-md-12">
<div class="table-responsive">
<table class="table" style="width: 100%;">
<tr>
<th class="action-th">Departemen</th>
<td><? echo $biodataSiswa['departemen']; ?></td>
</tr>
<tr>
<th class="action-th">Tahun Ajaran</th>
<td><? echo $biodataSiswa['tahunajaran']; ?></td>
</tr>
<tr>
<th class="action-th">Kelas</th>
<td><? echo $biodataSiswa['kelas']; ?></td>
</tr>
<tr>
<th class="action-th">NIS</th>
<td><? echo $biodataSiswa['nis']; ?></td>
</tr>
</table>
</div>
</div>
<input type="hidden" id="idmodul" name="idmodul" value="<? echo $idtabel; ?>"/>
<form id="filter-form">
<div class="row">
<? $no = 0;
foreach ($filter as $row) { ?>
<div class="col-md-3 col-sm-6 mb-3">
<label for=""><? echo $row?></label>
<select class="form-control" id="f_<? echo $no; ?>" name="f_<? echo $no; ?>">
<option value=''>Pilih</option>
<? foreach ($f_[$no] as $row) : ?>
<option value='<? echo $row['f1']; ?>'><? echo $row['f2']; ?> </option>
<? endforeach; ?>
</select>
</div>
<? $no++;} ?>
<br>
</div>
<div style="margin-top:20px;">
<input type="submit" name="submit" value="Filter" class="btn btn-primary d-inline">
</div>
</form>
<div class="row">
<div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example" style="width:100%;">
<thead>
<tr>
<th>Pelajaran</th>
<th>Nilai Angka</th>
<th>Nilai Huruf</th>
<th>Keterangan</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<!-- <div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example">
<thead>
<tr>
<th>Pelajaran</th>
<th>Nilai Angka</th>
<th>Nilai Huruf</th>
<th>Keterangan</th>
</tr>
</thead>
</table>
</div>
</div> -->
</div>
</div>
</section>
<div class="control-sidebar-bg"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var dataTable;
// var id = $('#idmodul').val();
dataTable = $('#example').DataTable({
"ajax": {
url : "<? echo base_url('viewtabel/ambil'); ?>",
type: "POST",
data: {
filter_data : function(){
return $('#filter-form').serialize();
},
idmodul : function(){
return $('#idmodul').val();
}
}
},
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
"aoColumns": [
{data : "f1"},
{data : "f2"},
{data : "f3"},
{data : "f4"}
],
"scrollCollapse": true,
"fixedColumns": {
"left": 1
},
'processing': true,
'language': {
"loadingRecords": ' ',
"processing" : '<i class="fa fa-spinner fa-spin" style="font-size:24px;color:rgb(75, 183, 245);"></i>'
},
"scrollX": true,
});
$('#filter-form').submit(function(e){
e.preventDefault();
dataTable.ajax.reload();
})
});
</script>
And, this is the Controller
<?
Header('Access-Control-Allow-Origin: *'); //for allow any domain, insecure
Header('Access-Control-Allow-Headers: *'); //for allow any headers, insecure
Header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); //method allowed
class Viewtabel extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper(array('path'));
$this->load->model('M_siswa');
$this->load->library('session');
$this->load->model('M_all');
$this->load->library('lib_connection');
$this->load->library('lib_menu');
$this->load->library('lib_menu_akademik');
$this->load->library('lib_changedate_toindo');
$this->load->library('lib_menu_departemen');
$this->db2 = $this->load->database('jibA', TRUE);
$this->db3 = $this->load->database('jibB', TRUE);
}
public function index() {
$accessToken = $this->session->userdata('token');
$link_api = $this->session->userdata('link_api');
$data['data_website'] = $this->M_all->getWesbiteData();
$arr_segment=$this->uri->segment_array();
if(isset($arr_segment[2])){
$action=strtolower(urldecode($arr_segment[2]));
} else
$action="";
switch($action){
default:
echo "Modul Tabel";
break;
case "load":
$data['data_website'] = $this->M_all->getWesbiteData();
$data['rows_menu3'] = $this->lib_menu_akademik->generate_menu();
$nis = $this->session->userdata('nis');
$emailtagihan = $this->session->userdata('email');
$bioSiswa = $this->M_siswa->getSiswaWithNis($nis,$emailtagihan);
$dataSiswa = $this->M_siswa->getDataByNis($nis);
$idKelas = $dataSiswa['idkelas'];
$id = $arr_segment[3];
$dataTabel = $this->M_all->getDataTabel($id);
$this->session->set_userdata('idmodul',$id = $arr_segment[3]);
$arrFilter = explode(',', $dataTabel['nama_filter']);
$arrQueryF = explode(' | ', $dataTabel['query_filter']);
$connection_id = $dataTabel['connection'];
$arrQueryF=str_replace('#NIS', "'".$nis."'",$arrQueryF);
$arrQueryF=str_replace('#DEPART', "'".$bioSiswa['departemen']."'",$arrQueryF);
// print_r($arrQueryF);
// print_R($arrQueryF);
for ($i = 0; $i < count($arrQueryF); $i++){
$arrQ[] = $this->M_siswa->getFilter($arrQueryF[$i]);
$data['f_'][$i] = $arrQ[$i];
}
$data['filter'] = $arrFilter;
// print_r($dataTabel['pk_tablebaru']);
$data['idtabel'] = $dataTabel['pk_tablebaru'];
$data['biodataSiswa'] = $bioSiswa;
$tglIndo = $this->lib_changedate_toindo->ubahIndo($bioSiswa['tgllahir']);
$data['tgllahirsiswa'] = $tglIndo;
$this->load->view("v_modultabel2.inc.php",$data);
break;
case "setting":
$ch5 = curl_init($link_api. 'extrarest/login-user');
curl_setopt($ch5, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $accessToken));
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true);
$oUser2 = json_decode(curl_exec($ch5));
$dept_uid = $oUser2->department;
$listmenu = $this->M_all->getMenuFromDepartemen($dept_uid);
$data['menuPerDept'] = $listmenu;
$data['menunya'] = $this->M_all->getMenu();
//$data['rows_menu'] = $this->lib_menu->generate_menu();
$data['rows_menu2'] = $this->lib_menu_departemen->generate_menu($dept_uid,$this->session->userdata('group'),$this->session->userdata('uid'));
$ch1 = curl_init($link_api. 'user/'. $this->session->userdata('uid'));
curl_setopt($ch1, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $accessToken));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
$oUser2 = json_decode(curl_exec($ch1));
if (!isset($oUser2)) {
print "Error accessing $link_api: \n" . curl_error($ch1);
}
elseif (isset($oUser2->error)) {
}
else {
}
curl_close($ch1);
$data['loguser'] = $oUser2;
$data['data_workspace'] = $this->M_all->getLinkApi1();
$data['data_website'] = $this->M_all->getWesbiteData();
//$mymenu=new Lib_menu();
//$ret=$mymenu-> generate_menu();
//$data=array('base_url'=>$base_url,'rows_menu'=>$ret);
//print_r($data['rows_menu']['level_1']);
$data_sidebar=$this->lib_menu->sidebar_menu();
$data['koneksi'] = $this->M_all->getAllConnection();
$this->load->view('v_modultabel2', $data);
$this->load->view("sidebar.php",$data_sidebar);
break;
case "post":
$nama_tabel = $this->input->post('nama_tabel');
$nama_filter = $this->input->post('nama_filter');
$query_filter = $this->input->post('query_filter');
$kolom_tabel = $this->input->post('kolom_tabel');
$query_data = $this->input->post('queryData');
$connection_id = $this->input->post('connection_id');
if($_POST['insert_mode']==1){
$postParams = array(
'pk_tablebaru' => '',
'nama_tabel' => $nama_tabel,
'nama_filter' => $nama_filter,
'query_filter' => $query_filter,
'kolom_tabel' => $kolom_tabel,
'query_data' => $query_data,
'connection' => $connection_id,
);
$this->M_all->InsertToTableBaru('tb_tablebaru',$postParams);
$last_id = $this->M_all->getLastIDTBBaru();
$l_id = $last_id['max(pk_tablebaru)'];
$url = base_url()."viewtabel/load/$l_id";
$this->db->query("UPDATE tb_tablebaru SET url = '$url' WHERE pk_tablebaru = '$l_id'");
redirect ('/viewtabel/setting/');
}
break;
case "del":
break;
case "ambil":
$filter_data = $this->input->post('filter_data');
parse_str($filter_data, $params);
$nis = $this->session->userdata('nis');
$idmodul = $this->session->userdata('idmodul');
$dataTabel = $this->M_all->getDataTabel($idmodul);
$queryDataTabel = $dataTabel['query_data'];
$queryDataTabel=str_replace('#NIS', "'".$nis."'",$queryDataTabel);
$queryDataTabel=str_replace('#f1','"'.$params['f_1'].'"',$queryDataTabel);
$queryDataTabel=str_replace('#f2','"'.$params['f_0'].'"',$queryDataTabel);
$getDatanya = $this->M_siswa->getDatanya($queryDataTabel);
print_r($queryDataTabel);
$json_data['data'] = $getDatanya;
echo json_encode($json_data);
break;
}
}
}
?>
at the Controller, i want to get the data from database. The variables used to enter the data are $getDatanya
This is the query :
SELECT c.nama AS f1,b.nilaiangka as f2,b.nilaihuruf as f3,b.keterangan as f4 FROM tabelB b LEFT JOIN tabelC c ON c.replid = b.idpelajaran LEFT JOIN tabelA a ON b.nis = a.nis AND a.aktif = 1 WHERE b.nis = #NIS AND b.idkelas = #f1 AND b.idsemester = #f2
Hopefully I can find a solution here. Thank you very much.
I am trying to get data from 2 tables in a mysql database. One of which has the id, name, surname, number and gender. The second table has id, product_name and price.
The first table information gets displayed in a html table with a drop down, that has a edit button.
The table gets populated with a while loop.
Once you click edit, a modal open with the name of the person and a drop down with all the products available, once you click on a product then it displays the product price.
My issue is that it only works with the first entry in the database where i can click on the product and it displays the price, anything after the first entry in the table, it does not want to display the price. Here is my code:
Table
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Phone Number</th>
<th>Gender</th>
</tr>
<?php
$sql = "SELECT * FROM test_table";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["surname"]; ?></td>
<td><?php echo $row["phone_number"]; ?></td>
<td><?php echo $row["gender"]; ?></td>
<td><ul class="t-dropdown-list">
<a data-toggle="modal" data-target="#SetProductCustomer<?= $row["id"]; ?>"><li class="t-dropdown-item">Edit</li></a>
</ul></td>
</tr>
<div class="modal fade" id="SetProductCustomer<?= $row["id"]; ?>" class="" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true">
<div class="modal-content">
<span class="close">×</span>
<p><?php echo $row['name']; ?> </p>
<select style="width: 100%;" name="" id="product_info" class="browser-default custom-select-new">
<?php
$records = mysqli_query($db, "SELECT * FROM products");
while ($data = mysqli_fetch_array($records)) {
echo '<option value="' . $data['product_name'] . '"
data-price="' . $data['price'] . '" >'
. $data['product_name'] . '</option>';
}
?>
</select>
<input type="text" name="price" id="price"/>
</div>
</div>
<?php
}
}
?>
</table>
SCRIPT TO GET THE PRICE
<script>
var mySelect = document.getElementById("product_info");
mySelect.addEventListener("change", function() {
var myNewOption = mySelect.options[mySelect.selectedIndex].getAttribute("data-price");
document.getElementById('price').value = myNewOption;
});
</script>
Okay so i appended the following to the ID in the select field and in the price input, which made it work.
<select style="width: 100%;" name="" id="product_info<?= $row["id"]; ?>"" class="browser-default custom-select-new">
<input type="text" name="price" id="price<?= $row["id"]; ?>"/>
and then just adjusted my Javascript to get those values
<script>
var mySelect = document.getElementById("product_info1");
mySelect.addEventListener("change", function() {
var myNewOption = mySelect.options[mySelect.selectedIndex].getAttribute("data-price");
document.getElementById('price1').value = myNewOption;
});
</script>
<script>
var mySelect = document.getElementById("product_info2");
mySelect.addEventListener("change", function() {
var myNewOption = mySelect.options[mySelect.selectedIndex].getAttribute("data-price");
document.getElementById('price2').value = myNewOption;
});
</script>
i want to make money value have commas in it, i know this question is already ask, but i kinda new to javascript or jquery in general, my problem is i dont know how to apply some of those code with mine
This is my jQuery code
<script>
$(function sum() {
console.log($('.calc'))
var sum = 0.0;
$('.calc').each(function() {
sum += parseInt($(this).text());
});
$("#subTotal").val(sum);
})();
function calculateSubTotal() {
var subtotal = $("#subTotal").val();
$("#subTotalDiscount").val(subtotal - (Math.round(($("#inputDiscount").val() / 100) * subtotal)));
var subtotal_discount = parseInt($("#subTotalDiscount").val());
$("#subTotalTax").val(Math.round(($("#inputTax").val() / 100) * subtotal_discount));
var subtotal_tax = parseInt($("#subTotalTax").val());
var pph = $("#inputpph").val();
$("#SubTotalpph").val(Math.round(parseInt($("#inputpph").val()*subtotal_discount)));
var subtotal_pph = parseInt($("#SubTotalpph").val());
var grandtotal = subtotal_discount + subtotal_tax + subtotal_pph;
$("#grandTotal").val(grandtotal);
}
</script>
This is my table code
<div class="row mt-3">
<div class="col-lg">
<div class="table-fix-head">
<table class="table table-fixed table-bordered table-hover" style="width:100%;" id="tebal">
<thead>
<tr>
<th scope="col">DKM No </th>
<th scope="col">Kode Produksi </th>
<th scope="col">Kode Barang </th>
<th scope="col">Deskripsi </th>
<th scope="col">Jumlah/Quantity </th>
<th scope="col">Unit </th>
<th scope="col">Unit Price </th>
<th scope="col">Sub Total </th>
</tr>
</thead>
<tbody>
<?php $i = 1;
foreach ($query as $kiki) : ?>
<tr class="table-row">
<td><?php echo $i++; ?></td>
<td><?php echo $kiki["kodeprod"]; ?></td>
<td><?php echo $kiki["kodebarang_op"]; ?></td>
<td><?php echo $kiki["catatan"]; ?></td>
<td><?php echo $kiki["qty_op"]; ?></td>
<td><?php echo $kiki["unit_op"]; ?></td>
<td><?php echo $kiki["price"]; ?></td>
<td class="calc"><?php echo $kiki["qty_op"]*$kiki["price"]; ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
</div>
what i want is that the number in my table and my output value have commas like '122.000.000'
the table preview : https://i.imgur.com/akbfJku.png
form :
<div class="form-group">
<div class="row">
<div class="col-lg-3">
<label for="total" class="label-control" id="labelsubtotal">Total : </label>
</div>
<div class="col-lg-9">
<input type="number" value="" style="text-align: right;" class="form-control money" id="grandTotal" name="grandTotal" disabled>
</div>
</div>
</div>
By doing a javascript function
function commasNumber(yourMoneyValue) {
return yourMoneyValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
or by using your example
function commasNumber() {
var subtotal = $("#subTotal").val();
var valueWithCommas = subtotal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$("#subTotal").val(valueWithCommas);
}
By modifying t hj's answer, you could replace and also remove the commas for the purpose of calculating the prices :
<script>
$(document).ready(function () {
console.log($('.calc'))
var sum = 0.0;
$('.calc').each(function () {
sum += parseInt($(this).text());
});
$("#subTotal").val(addCommas(sum));
});
function calculateSubTotal() {
var subtotal = removeCommas($("#subTotal").val());
$("#subTotalDiscount").val(addCommas(+subtotal - (Math.round(($("#inputDiscount").val() / 100) * subtotal))));
var subtotal_discount = parseInt(removeCommas($("#subTotalDiscount").val()));
$("#subTotalTax").val(addCommas(Math.round(($("#inputTax").val() / 100) * subtotal_discount)));
var subtotal_tax = parseInt(removeCommas($("#subTotalTax").val()));
var pph = $("#inputpph").val();
$("#SubTotalpph").val(addCommas(Math.round(parseInt(pph * subtotal_discount))));
var subtotal_pph = parseInt(removeCommas($("#SubTotalpph").val()));
var grandtotal = subtotal_discount + subtotal_tax + subtotal_pph;
$("#grandTotal").val(grandtotal);
}
function addCommas(moneyValue) {
return moneyValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
function removeCommas(moneyValue) {
return moneyValue.toString().replace(".", "");
}
</script>
You can use javascript like #t-hj post or if you want to use PHP, here's some example
<?php echo number_format($kiki["price"], 0, '', ',') ?>
Read more about PHP number_format
I have searched the whole WWW but get nothing helpful. Any Solution will be appreciated. thanks in advance
MY HTML
<div class="row">
Either the form tag needed in my case or not
<form>
<div class="form-group">
<label for="date" class="col-12 col-md-2 control-label"><?php echo 'Date';?>
</label>
<div class="col-12 col-md-3">
<input type="text" class="datepicker form-control" name="date" id="date">
</div>
</div>
Here I am getting the data from my database
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
I am using datatable class for exporting and printing
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
<th><div><?php echo get_phrase('options');?></div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach($attendance as $row):?>
$attendance is recieved from the controller in $this->load->view('backend/index', $page_data);
<tr>
<td><?php echo $count++;?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['student_id'];?></td>
<td><?php echo $row['class_id'];?></td>
<td><?php echo $row['date'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
MY JavaScript
The script below alert() the class_id and date but do not pass anything to the controller function
<script type="text/javascript">
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {"class_id": class_id, "date": date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
}
});
}
</script>
My Controller
If I give static value to $date and $class_id as $date = '04-04-2018'; $class_id = 2; inside manage_attendance() below it works but using $this->input->post() do nothing:
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1)
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
$this->load->view('backend/index', $page_data);
}
Try to change
url: '<?php echo base_url();?>index.php?admin/manage_attendance'
to
url: '<?php echo base_url();?>index.php/admin/manage_attendance',
You have to append data like this using jquery:
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {class_id: class_id, date: date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
var resultData = JSON.parse(response);
if(resultData!=null){
attendance= resultData.length;
}
if(attendance>0){
for(i=0;i<attendance;i++){
$(".attendance_listing").append("<tr><td>"+resultData[i].status+"</td><td>"+resultData[i].student_id+"</td><td>"+resultData[i].class_id+"</td><td>"+resultData[i].date+"</td></tr>");
}
}
}
});
}
//controler
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1){
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
echo json_encode($page_data);
}
}
I can get the same result by coding as following but I do not prefer that method/logic I want something as I have posted above
HTML
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
</tr>
</thead>
<tbody id="putdatahere">
</tbody>
</table>
JavaScript
<script type="text/javascript">
function get_attendance() {
var e = document.getElementById("class_id");
var class_id = e[e.selectedIndex].value;
var date = $('#date').val();
$.ajax({
url: '<?php echo base_url();?>index.php?admin/manage_attendance/'+ date +'/' + class_id,
success: function(response)
{
jQuery('#putdatahere').html(response);
}
});
}
</script>
CodeIgniter Controller
function manage_attendance($date, $class_id){
$query = $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
if($query){
$html_return = "";
foreach ($query as $attendance) {
$html_return .="<tr><td>";
$html_return .= $attendance['status']; //further Proccessing here e.g if $attendance['status'] == 0 echo absent otherwise present
$html_return .="</td><td>";
$html_return .= $attendance['student_id']); //further Proccessing here e.g get student name from its student_id
$html_return .="</td><td>";
$html_return .= $attendance['class_id']; //further Proccessing here e.g get class name from its class_id
$html_return .= "</td><td>";
$html_return .= $attendance['date'];
$html_return .="</td></tr>";
}
echo $html_return;
} else {
echo 'No record';
}
}
this is code of search.php. i want to take search by date from the input box as below.
<form action="visitor-print.php">
<div class="col-sm-3 text-center"><h3>Date</h3>
<input type="text" class="form-control" name="dat" placeholder="Enter Date">
<p class="help-block">Month Format 1,2,3,....29,30..</p>
<button class="btn btn-default"><span>Submit</span></button>
</div>
</form>
this is my visitor-print.php code where i get undefined index error on dat (which is from the other page)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('visitor_list');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM list1 WHERE d1 = '". $_POST["dat"] . "' ";
$retval = mysql_query( $sql,$conn ) or die("Error: ".mysql_error($conn));
?>
<div class="container">
<h3 class="text-center">User Feed-Back Details</h3><br />
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<tr>
<th width="10%">Visitor Name</th>
<th width="10%">Address</th>
<th width="10%">Area to Visit</th>
<th width="10%">Phone No.</th>
<th width="20%">Want to meet with </th>
<th width="50%">Purpose of meeting</th>
</tr>
<?php
while($row = mysql_fetch_array($retval,MYSQLI_BOTH))
{
?>
<tr>
<td><?php echo $row['nm']; ?></td>
<td><?php echo $row['add1']; ?></td>
<td><?php echo $row['area_vis']; ?></td>
<td><?php echo $row['y1']; ?></td>
<td><?php echo $row['app_ty']; ?></td>
<td><?php echo $row['no_per']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
<div align="center">
<button name="create_excel" id="create_excel" class="btn btn-success">Create Excel File</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('#create_excel').click(function(){
var excel_data = $('#employee_table').html();
var page = "excel.php?data=" + excel_data;
window.location = page;
});
});
</script>
Problem:
Notice: Undefined index: dat in D:\wamp\www\radissun visitor\visitor-print.php on line 12
and is not showing data from mysql
The answer you are looking for: You are using $_POST - which is just for forms which have method="post". Default method is GET - so your variables are $_GET[]. You can either set the method parameter in the html to POST, or you change your PHP code to GET.
But I must point out, that your code is not usable for productive environments, as it is vulnerable to SQL Injection. See http://www.w3schools.com/sql/sql_injection.asp
MISSING METHOD ON FORM METHOD="POST"
NOTE: IF YOU USE METHOD="POST" YOU CAN GET VALUE BY $_POST['dat']; IF YOUR NOT USING METHOD ATTRIBUTE .FORM JUST SUBMITED AS GET METHOD YOU CAN GET BY $_GET['dat'];
<form action="visitor-print.php" METHOD="POST" >
MISSING FORM SUBMIT
<INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="SUBMIT" >
(OR)
ADD TYPE="SUBMIT" TO BUTTON
<button TYPE="SUBMIT" class="btn btn-default"><span>Submit</span></button>