Codeigniter: Using button click to view more data from database - javascript

Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.
Question: How can I retrieve location and email of a user when the button is clicked specifically?
Example:
user1, joe doe, [button] -> user1 location, user1#email.com
user2, jay doe, [button] -> user2 location, user2#email.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
$config = array();
$config['base_url'] = base_url() . "controller/pagination";
$total_row = $this->model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 8;
$config['uri_segment'] = 3;
/* $config['use_page_numbers'] = TRUE; */
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = '<span aria-hidden="true">»</span>';
$config['prev_link'] = '<span aria-hidden="true">«</span>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ', $str_links);
// View data according to array.
$this->load->view("view-employees", $data);
}
model.php
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
view.php
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data->username; ?></td>
<td><?php echo $data->name; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data->location;
echo $data->email;
?>
</button>
</td>
</tr>

You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data
Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller

Try like this..
MODEL:
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
return false;
}
View:
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['name']; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data['location'];
echo $data['email'];
?>
</button>
</td>
<?php } ?>
</tr>

Related

How to display group data based on end date?

I have a table like below:
How can i display the data based on task end date with new table. Meaning that, the full <div tag`` will repeat for each ending date and display the records on columns. For example-
**Staff 1**
Date: 2020-11-14
Date: 2020-11-27
**Staff 2**
Date: 2020-11-14
Thanking in anticipation.
<div>
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Task Name</th>
<th>Remarks</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
<?php
$sql = "SELECT * FROM dl_fullremarks ";
$result = mysqli_query($conn, $sql);
foreach ($result as $row) {?>
<tr>
<td><?php echo $row['staff_id']; ?></td>
<td><?php echo $row['task_name']; ?></td>
<td><?php echo $row['task_remarks']; ?></td>
<td><?php echo $row['task_startdate']; ?></td>
<td><?php echo $row['task_enddate']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
You can fetch your data first with SQL and then organize it with a PHP associative array :
$data = [];
foreach ($result as $row) {
// Check if the current end date is part of the array. If not, add it
if (!isset($data[$row['task_enddate']]) {
$data[$row['task_enddate']] = [];
}
// Add the row to the assigned end date
$data[$row['task_enddate']][] = $row;
}
$data nows contains the following structure :
[
'2020-11-14' => [
['staff_id' => 1, 'task_name' => 'name', // ...],
['staff_id' => 2, 'task_name' => 'other name', // ...],
],
'2020-12-16' => [
['staff_id' => 3, 'task_name' => 'name', // ...],
],
]
You can now loop through it to display your template :) !
foreach ($data as $date => $rows) {
echo '<div>';
echo "<div>$date</div>";
echo '<div class="row">';
foreach ($rows as $row) {
// Display your row data here
}
echo '</div></div>';
}
Group result set by task_endtime:
SELECT * FROM dl_fullremarks
WHERE staff_id = '1'
ORDER BY task_endtime
When task_endtime changed from last saved then print header. All other rows are printed as in your example.
$prev_endtime = null
foreach ($result in $rows) {
if (date('Y-m-d', $row['taks_endtime']) != $prev_endtime) {
echo '<div class="header">date formatted here</div>';
$prev_endtime = date('Y-m-d', $row['task_endtime']);
}
echo '<div class="row">row cells gere</div>';
}

Call php function from Javascript inside php file

I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!

Insert multiple records in single checkbox in codeigniter?

I've two different table, 1st is draft_table, and 2nd is fix_table, each table have same fields ( product & price )
i want to make data from draft_table, can be save to fix_table with checkbox, so just selected data will save to fix_table.
i've code like this :
AJAX
<script>
$(function(){
$("a.paid").click(function(){
if(confirm("Are you sure want save this?"))
{
id_array=new Array()
i=0;
$("input.chk:checked").each(function(){
id_array[i]=$(this).val();
i++;
})
$.ajax({
url:'<?php echo base_url(); ?>fix_data/set',
data:"kode="+id_array,
type:"POST",
success:function(respon)
{
if(respon==1)
{
window.parent.location.reload(true);
}
}
})
}
return false;
})
})
</script>
Views :
<?php
foreach($data_get->result_array() as $dp)
{
?>
<tr><td><input type="checkbox" name="chk[]" class="chk" value="<?php echo $dp['id_draft']; ?>" /></td>
<td><?php echo $dp['product']; ?></td>
<td><?php echo $dp['price']; ?></td>
</td></tr>
<?php
}
?>
Controller :
public function set_stts()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$dt = $this->db->get_where("tbl_draft",$id_get)->row();
$product = $dt->product;
$price = $dt->price;
if ($this->input->post('kode')) {
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES (".$product.",".$price.")");
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
After i Click submit in draft form, nothing happen, is there anyone may help me with this case?
Thank you
maybe you can change your controller like this :
public function set()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$quer = $this->db->query("select * from tbl_draft WHERE id IN (".$id_get.")");
if ($this->input->post('kode')) {
foreach($quer->result_array() as $dp)
{
$a = $dp['product'];
$b = $dp['price'];
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES
('".$a."','".$b."')");
}
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}

Posting dynamic arrays as distinct variables using JavaScript

Am trying to dynamically add the fields for subjects and the grades obtained, but am getting an error "Undefined index: subject in..." when posting those variables using java script.
Could there be something am missing with my posting mechanism. Notice that in the form data am not puting id="subject" to avoid picking the id for only one subject, and am using name="subject[]" to show an array, but I
dont seem to know how to represent this in the java script as we will see below.
form data as follows;
<tr>
<td colspan="6"><div align="center"><strong>
<p style="color:#930">Academic Qualification</p>
</strong></div></td>
</tr>
<?php
require_once("connection/connectPDO.php");
$sql="CALL sp_getSubjects()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultsSubject = $pdo->query($sql);
foreach($resultsSubject as $rowSubject)
{
?>
<tr>
<td width="35%" colspan="3"><div align="right"><?php echo $rowSubject['SubjectName']; ?>:<input name="subject[]" type="hidden" value="<?php echo $rowSubject['SubjectID']; ?>" /></div></td>
<td width="65%" colspan="3"><select name="grades[]" id="grades" class="validate[required]">
<option value="">--Select Grade--</option>
<?php
$sql="CALL sp_grabGrades()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultset = $pdo->query($sql);
foreach($resultset as $row)
{
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php } ?>
</select></td>
<?php } ?>
</tr>
the form looks like this
Academic Qualification
English <--select-->
Biology <--select-->
Science <--select-->
the java script code is as follows;
$(document).ready(function(){
$("#submit").click(function(){
//if invalid do nothing
if(!$("#formD").validationEngine('validate')){
return false;
}
var vgrades = $("#grades").val();
var vsubject = $("#subject").val();
$.post("sendInitialApplication.php",
{
grades : vgrades,
subject : vsubject
/*Handles response from server*/
function(response){
alert(response);
});
alert("You are here");
});
});
the PHP code "sendInitialApplication.php" is as follows
<?php
$method = $_SERVER['REQUEST_METHOD'];
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=student', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
/*Checks if method is HTTP POST*/
if(strtolower($method) == 'post'){
$grades = addslashes($_POST['grades']);
$subjects = addslashes($_POST['subject']);
try {
$dbHandler = connect();
$dbHandler->beginTransaction();
//Saving Various subjects with distinct grade obtained
foreach($subjects as $key => $subject)
{
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grades[$key]);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
$dbHandler->commit();
echo "The Operation was Successful!!!!!!";
} catch (PDOException $e) {
$dbHandler->rollback();
die($e->getMessage());
}
}else{
echo "Oops! Make sure Method is POST";
}
?>
I'm expecting that $_POST['subject'] and $_POST['grades'] should be array. Than you cannot use $subjects = addslashes($_POST['subjects']), but $subjects = $_POST['subjects']. Calling addslashes on array throws PHP warning and returns NULL.
Edit:
I suggest modify logic of your code.
Input type hidden, with subject id, will not work, as you expects. Modify your list:
// ... obtaining subjects from db ...
foreach($resultsSubject as $rowSubject) {
?>
<tr>
<td>
<select name="grade[<?= $rowSubject['SubjectID']; ?>]">
<option value="">--Select Grade--</option>
<?php
// ... obtaining grades from db ...
foreach($resultset as $row) {
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
Than serialized form should return array:
grade = array (
subjectID1 => selectedGradeId,
subjectID2 => selectedGradeId,
...
)
And data processing in sendInitialApplication.php:
// prepare db transaction
$grades = $_POST['grade'];
foreach ($grades as $subject => $grade) {
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grade);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
// close db transaction

ajax to receive data from database request does not work

I'm a really beginner in the ajax domain, and I really need help.
In fact I have done a query to receive some data from a database.
Here on the header I have:
<script type="text/javascript">
<?php if(isset($_GET['p']) AND $_GET['p']=='create_dossier') {?>
function writeInDiv(text){
var objet = document.getElementById('code_client');
objet.innerHTML = text;
}
function ajax()
{
var xhr=null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "ajaxclient.php?code_client=<?php echo $_GET['code_client'] ; ?>", false);
xhr.send(null);
writeInDiv(xhr.responseText);
setInterval("ajax()",5000);
}
<?php }?>
</script>
on the page ajaxclient.php I have the following code:
<?php require_once('Connections/localhost.php'); ?><?php mysql_select_db( $database_localhost ); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<table width="100%" border="0" id="box-table-a">
<tr>
<th scope="col" width="15%">CODE CLIENT</th>
<th scope="col" width="15%">RAISON SOCIALE</th>
<th scope="col" width="55%">ADRESSE </th>
<th scope="col" width="15%">ACTION</th>
</tr>
<?php
$code_client=$_GET["code_client"];
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
{?>
<tr>
<td><?php echo $donnees['code_client'] ; ?></td>
<td><?php echo $donnees['raison_sociale'] ; ?></td>
<td><p align="left"> <?php echo $donnees['rue'].'<br>'.$donnees['complement1'].'<br>'.$donnees['complement2'].'<br>'.$donnees['code_postal'].' - '.$donnees['ville'].'<br>'.$donnees['pays'] ; ?></p></td>
<td><a href="index.php?p=create_dossier2&code_client=<?php echo $data['code_client'] ; ?>"><img src="images/001_18.gif" width="24" height="24" /></td>
</tr>
<?php }
?></table>
</body>
</html>
The page called create_dossier.php contain:
<form action="#" method="get"><fieldset>
<legend>CRÉANCIER</legend>
<br />
<label>Raison sociale:</label><input type="hidden" name="p" value="create_dossier" /> <input type="text" name="code_client" onkeypress="form.submit()" /></fieldset><p align="center"><input type="submit" name="enreg" value="Chercher !" /></form>
What I would like is to display the data without sending the page and the thing is that it always send the form before returning any data. For that I do not need ajax.
I really do not know what wrong and how to correct it.
You should returning the result of query as XML or JSON and filling the tables with XML in calling file.
This is an example php.file (Need to convert to PDO)
require("dbinfo.php");
// Get parameters from URL
$code_client=$_GET["code_client"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("client");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("'code_client'", $row['code_client']);
//$newnode->setAttribute("xxx", $row['xx']); list all other
}
}
echo $dom->saveXML();
?>
in fact, you should prevent form submitting like this:
onclick="return doSomeAction();"
function doSomeAction() {
// create XHR object
// send data
// handle response
return false;
}
doSomeAction() = ajax() in your case
don't forget to return false

Categories