I am working with my project in school. How can i get the value of selected checkbox in data table. I am using a codeigniter framework and i am populating my data table in controller and passed it to the view. Now i want to something alert/output the user_id of the checked data table. What i really want is to save the values of the checked user_id in my database table.
Here is my controller for populating the data table:
public function getalldocs()
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value=" "'.$docs->user_id.'" " type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
in my view, here is the ajax for data table:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
$(document).ready(function() {
$('#dataTables-docs').dataTable();
show_docs();
});
You can get data from row table using this code:
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var row = $(this).closest('tr');
var data = table.row(row).data();
var rowData = data[1];
alert(rowData);
});
Return the data of row selected from checkbox, if you want get the value of checkbox (user_id), then you can use this code:
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
alert(user_id);
});
Result: https://jsfiddle.net/cmedina/7kfmyw6x/130/
Related
I am using code igniter, google charts with php and MySQL to display charts. It works using fixed query. I am trying to add a dropdown to display the chart based on the option (sql column "status") selected
Here is what I have so far. How can I modify this to accept dropdown values?
model.php
public function get_chart_data()
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(rating) AS Count');
$this->db->from('db_mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
$results['chart'] = $query->result();
}
controller.php
$this->load->model('model', 'chart');
public function index() {
$results = $this->chart->get_chart_data();
$data['chart'] = $results['chart'];
$this->load->view('index.php', $data);
}
view.php
<?php
foreach ($chart as $object) {
$open_all[] = "['".$object->rating."', ".$object->Count."]";
}
?>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart_open);
function drawChart_open() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Rating');
data.addColumn('number', 'Count');
data.addRows([
<?php echo implode(",", $open_all);?>
]);
var options = {
pieSliceText: 'value-and-percentage',
};
var chart = new google.visualization.PieChart(document.getElementById('open_div'));
chart.draw(data, options);
}
<div id="open_div" class="chart"></div>
Thanks in advance!
UPDATE:
I have tried the below using ajax but it doesn't seem to work. I am definitely sure I am doing something wrong here but not sure where. Using Inspect in chrome also doesn't give any errors.
model.php
public function fetch_result($status)
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(status) AS Status_Count');
$this->db->from('db__mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
return $query;
}
controller.php
$this->load->model('model', 'chart');
public function mychart() {
if(!empty($_POST["val"])) {
$val=$_POST["val"];
$result_new=$this->chart->fetch_result($val);
$array = array();
$cols = array();
$rows = array();
$cols[] = array("id"=>"","label"=>" Rating","pattern"=>"","type"=>"string");
$cols[] = array("id"=>"","label"=>"Count","pattern"=>"","type"=>"number");
foreach ($result_new as $object) {
$rows[] = array("c"=>array(array("v"=>$object->risk_rating,"f"=>null),array("v"=>(int)$object->Status_Count,"f"=>null)));
}
$array = array("cols"=>$cols,"rows"=>$rows);
echo json_encode($array);
}
}
view.php
function drawChart_open_all(num) {
var PieChartData = $.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "dashboard/chart/mychart",
data:'val='+num,
dataType:"json"
}).responseText;
alert(PieChartData);
// Create the data table.
var data = new google.visualization.DataTable(PieChartData);
var options = {
pieSliceText: 'value-and-percentage',
};
var chart = new google.visualization.PieChart(document.getElementById('open_new'));
chart.draw(data, options);
}
<div><span> <b>Pie Chart<br /><br /></span></div>
<form>
<select name="status" onchange="drawChart_open_all(this.value)">
<option value="WIP">WIP</option>
<option value="Close">Close</option>
</select>
</form>
<div id="open_new" class="chart"></div>
Thanks in advance!!
I think the easiest thing would be to send a GET request with the <option> value
First, go back to your first version.
Next, send the value in your onchange event
function drawChart_open_all(num) {
location = "<?php echo base_url(); ?>" + "dashboard/chart/mychart?option=" + num;
}
Then in Model --
get_chart_data()
you should be able to access the value with --
$_GET['option']
use that to modify your query
here's an old answer with similar concept -- difference is it uses POST vs. GET
and a <form> with a <input type="submit"> button to send the request
How to pass JavaScript variables to PHP?
I managed to figure out what the problem was and used ajax in the end. #WhiteHat solution led to also in the right direction. Thanks for that!
model.php
public function fetch_result($status)
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(status) AS status_count');
$this->db->from('db_mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
$results_new = $query->result(); // <-- Forgot to add this!
return $results_new;
}
controller.php
$this->load->model('model', 'chart');
public function mychart() {
if(!empty($_POST['option'])) {
$val = $_POST['option'];
$result_new=$this->chart->fetch_result($val);
$array = array();
$cols = array();
$rows = array();
$cols[] = array("id"=>"","label"=>" Rating","pattern"=>"","type"=>"string");
$cols[] = array("id"=>"","label"=>"Count","pattern"=>"","type"=>"number");
foreach ($result_new as $object) {
$rows[] = array("c"=>array(array("v"=>(string)$object->rating),array("v"=>(int)$object->status_count)));
}
$array = array("cols"=>$cols,"rows"=>$rows);
echo json_encode($array);
}
}
view.php
function drawChart_open_all(status) {
var PieChartData = $.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "dashboard/chart/mychart",
data: { 'option':status }, // <-- kept as option instead of val
dataType:"json",
global: false, // <-- Added
async:false, // <-- Added
success: function(data){ // <-- Added
return data; // <-- Added
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
}).responseText;
// Create the data table.
var data = new google.visualization.DataTable(PieChartData);
var options = { pieSliceText: 'value-and-percentage', };
var chart = new google.visualization.PieChart(document.getElementById('open_new'));
chart.draw(data, options);
}
<div><span> <b>Pie Chart<br /><br /></span></div>
<form>
<select name="status" onchange="drawChart_open_all(this.value)">
<option value="WIP">WIP</option>
<option value="Close">Close</option>
</select>
</form>
<div id="open_new" class="chart"></div>
I was able to succesfully get data from database in json format from controller, this is how it looks:
{
"dealer":[
["1","himanshu"],
["2","bhola the dealer"],
["3","bhola the dealer"]
]
}
the problem is that I am not able to pass json data into the dropdown list in view from the controller.
Model Code:
public function getName(){
$this->db->select('dealerid,dealername');
$query=$this->db->get('Dealer');
$result=$query->result_array();
//echo "<pre>";
return $result;
}
Controller Code:
public function dealer_list()
{
$list = $this->person->getName();
$ddata = array();
foreach ($list as $person) {
$row = array();
$row[] = $person['dealerid'];
$row[] = $person['dealername'];
$ddata[] = $row;
}
$output = array(
"dealer" => $ddata,
);
//output to json format
echo json_encode($output);
}
View Code:
//get a reference to the select element
$select = $('#select');
//request the JSON data and parse into the select element
$.ajax({
url: "<?php echo site_url('dealer_controller/dealer_list')?>"
, dataType: 'JSON'
, success: function (data) {
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.dealer, function (key, val) {
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
}
, error: function () { <strong>
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
Your json output doesn't have the keys id or name for each dealer. Therefore val.id and val.name won't work.
In your Controller change:
$row[] = $person['dealerid'];
$row[] = $person['dealername'];
to:
$row["id"] = $person['dealerid'];
$row["name"] = $person['dealername'];
This adds the keys id and name to the php array, and when converted to json should output something like the following:
{"dealer":[{"id": "1", "name": "himanshu"}, {...}]}
These can then be retrieved in your $.each with val.id and val.name
Fiddle
$.each(data.dealer, function (index, item) {
$select.append(
$('<option>', {
value: item[0],
text: item[1]
}, '</option>'))
}
)
})
We are making a website using PHP and Knockoutjs. We are able to sent the JSON data using $.ajax method in Knockoutjs.
But it is not loading the data requested initially.
PHP code
$students = $db->query("SELECT * FROM students WHERE status = 1");
$students_r = array();
while($row = $students->fetch_array()){
//default student data
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
//update status
//its false by default since
//this is only true if the user clicks
//on the span
//$name_update = false;
// $age_update = false;
//build the array that will store all the student records
$students_r[] = array(
'id' => $id, 'name' => $name, 'age' => $age,
);
}
echo json_encode($students_r); //convert the array to JSON string
and this is actually generating proper json data
[
{"id":"1","name":"monkey d. luffy","age":"15"},
{"id":"4","name":"son goku","age":"30"},
{"id":"5","name":"naruto uzumaki","age":"16"},
{"id":"6","name":"draco","age":"15"},
{"id":"10","name":"NIklaus MikaelSon","age":"1500"},
{"id":"16","name":"Elijah","age":"1000"},
{"id":"19","name":"Chitrank","age":"23"},
{"id":"20","name":"Rahul","age":"24"}
]
Now Knockout comes into play to show this data on the page, So here is the HTML page
function RefreshUser(data) {
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
};
var personModel = function(id, name, age){
var self = this; //caching so that it can be accessed later in a different context
this.id = ko.observable(id); //unique id for the student (auto increment primary key from the database)
this.name = ko.observable(name); //name of the student
this.age = ko.observable(age);
this.nameUpdate = ko.observable(false); //if the name is currently updated
this.ageUpdate = ko.observable(false); //if the age is currently updated
//executed if the user clicks on the span for the student name
this.nameUpdating = function(){
self.nameUpdate(true); //make nameUpdate equal to true
};
//executed if the user clicks on the span for the student age
this.ageUpdating = function(){
self.ageUpdate(true); //make ageUpdate equal to true
};
};
var model = function(){
var self = this; //cache the current context
this.person_name = ko.observable(""); //default value for the student name
this.person_age = ko.observable("");
this.person_name_focus = ko.observable(true); //if the student name text field has focus
this.people = ko.observableArray([]); //this will store all the students
this.createPerson = function(){
if(self.validatePerson()){ //if the validation succeeded
//build the data to be submitted to the server
var person = {'name' : this.person_name(), 'age' : this.person_age()};
//submit the data to the server
$.ajax(
{
url: 'refresher_save.php',
type: 'POST',
data: {'student' : person, 'action' : 'insert'},
success: function(id){//id is returned from the server
//push a new record to the student array
self.people.push(new personModel(id, self.person_name(), self.person_age()));
self.person_name(""); //empty the text field for the student name
self.person_age("");
}
}
);
}else{ //if the validation fails
alert("Name and age are required and age should be a number!");
}
};
this.validatePerson = function(){
if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
return true;
}
return false;
};
$.getJSON("refresher_save.php", function(userModels) {
var t = $.map(userModels.people, function(item) {
console.log("Something");
return new RefreshUser(item);
});
self.people(t);
});
this.removePerson = function(person){
$.post(
'refresher_save.php',
{'action' : 'delete', 'student_id' : person.id()},
function(response){
//remove the currently selected student from the array
self.people.remove(person);
}
);
};
this.updatePerson = function(person){
//get the student details
var id = person.id();
var name = person.name();
var age = person.age();
//build the data
var student = {'id' : id, 'name' : name, 'age' : age};
//submit to server via POST
$.post(
'refresher_save.php',
{'action' : 'update', 'student' : student}
);
};
};
ko.applyBindings(new model());
Now here we are using $.getJSON to fetch all the JSON records, but it is not displaying the data on the page.
i can see little mistakes for example
this.people = ko.observableArray([]);
and others you should recheck your code i think they should be self.people..... self.person_age, later in your code you refer to them with self for example here
self.people.push(new personModel(id,
self.person_name(),self.person_age()));
you refer with self thats why the data is not loading you are not refering to the same object people
I see you have tried to create something based on a code from two sources (you have them scrambled), which are looking similar but simple are not the same (are not providing correct data).
First you are creating logic duplicity with RefreshUser() and personModel(). You should to left only personModel() as
var personModel = function(data){
var self = this;
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
/* all the rest stays the same */
Then in createPerson() you should to update that line
self.people.push(new personModel(person));
Then finaly $.getJSON part should to looks like
$.getJSON("refresher_save.php", function(allData) {
var data = $.map(allData, function(item) { return new personModel(item) });
self.people(data);
});
and should be located at the bottom of model() view.
Thank you for your time, but my problem has been been solved, actually in my php script I was passing unused parameters, that cause the problem, when I removed those parameters, it worked and database values loaded when page refreshes. Thank you for your replies. :)
I am trying to only update the page when their are updates in the database but i am unsure how to do that.
I was thinking of comparing ids stored into the database because each ID is unique so if i make some sort of expression that compares the current array stored or picked up by AJAX to the ids in the database. But i am unsure how to compare ids and check if their is a new update
Any help would be appreciated
Controller
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$id = array();
$arr = array();
$arr2 = array();
foreach($queryresults as $row)
{
$id[] = $row->id;
$arr[] = $row->post;
$arr2[] = $row->img;
}
$data = array();
$data[] = $id
$data[] = $arr;
$data[] = $arr2;
echo json_encode($data);
}
View
<script type='text/javascript' language='javascript'>
$('#getdata').click(function () {
$.ajax({
url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
async: false,
type: "POST",
success: function(data) {
// thought i could do something like
if(data.change in database) do bla bla
var id = data[0];
var arr = data[1];
var arr2 = data[2]
}
})
});
</script>
There is a simple way to do this.
create a session variable and assign it the last id. than on the page take this session id on a hidden input.
Now when you are sending ajax request you can take hidden input's value and send it to controller function where you can query for last id. If last id from query is not equal to session id you should echo other wise echo 0. in ajax request check if response is coming from controller and it is greater than 0 change the page with new id. Than update the session id with ajax
I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";