I am getting an error[object Object] while trying to pass a value through ajax calls. I am using jquery selector to get value of checkbox. And trying to pass it through ajax so that I can get only the checkbox value that I have selected. But getting an error. Thanks.
Here is my code:
dashboard.php
if($param['aktion'] == 'save-widget-vehicle')
{
$page['register-fahrzeuge'] = array(
1 => array( 'Fahrzeug','aktiv',$page['script'],''),
0 => array( 'Edit-Fahrzeug','enabled',$page['script'],'',''),
);
$opts = !empty($param['filterOpts']) ? $param['filterOpts'] : array();
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}
$query =
'SELECT Fahrzeuge.dsnr,name
FROM Fahrzeuge
INNER JOIN ohne_fahrzeuge ON Fahrzeuge.dsnr = ohne_fahrzeuge.dsnr
WHERE Fahrzeuge.name IN ('.implode(",", $tmp).')';
$result = mysql_query($query, $myConnection);
$data = array();
$html = '<table width="538" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div>'.CreateRegister($page['register-news']).'</div>
'.CreateMessage().'
<div class="cont-liste-verlauf register"> ';
while($row = mysql_fetch_array($result)){
//$news_result = $fahrzeuge['name'];
$html .= '<table id="fahrzeuge">
<tr>
<td>
'. $data[] = $row .'
</td>
</tr> ';
}
$html .= '</table>
</div>
</td>
</tr>
</table>';
$return = array(
'status' => 1,
'html' => $html
);
echo json_encode($return);
die();
$param['aktion'] = 'get-widget-vehicle';
}
dashboard.js
function getFahrzeuge() {
var opts = [];
$("input[type=checkbox]").each(function () {
if (this.checked) {
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
// $('#fahrzeuge').html(makeTable(records));
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
if($(this).attr('id') == 'submitId')
var opts = getFahrzeuge();
saveFahrzeugeWidget(opts);
});
var allFahrzeuge = [];
$("input[type=checkbox]").each(function(){
allFahrzeuge.push($(this)[0].id)
})
Related
I'm trying to do this example https://datatables.net/blog/2017-03-31 everything works except the ajax request, the problem is that I'm trying to return data from a database and a barely know how to do it with ajax (newbie) this is how my code and ajax request look:
var id = 0;
$('#tablanormal tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var tdi = tr.find("i.fa");
var row = table.row(tr);
id = 0;
id = parseInt(table.row(this).data().id_sol);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
tdi.first().removeClass('fa-minus-square');
tdi.first().addClass('fa-plus-square');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
tdi.first().removeClass('fa-plus-square');
tdi.first().addClass('fa-minus-square');
}
});
table.on("user-select", function (e, dt, type, cell, originalEvent) {
if ($(cell.node()).hasClass("details-control")) {
e.preventDefault();
}
});
});
function format(rowData) {
var div = $('<div/>')
.addClass('loading')
.text('Loading...');
$.ajax({
method: 'POST',
url: 'datatables_ajax/items.php',
data: {idsol: id},
dataType: 'json',
success: function (json) {
div
.html(json.html)
.removeClass('loading');
},
error: function (er) {
console.error(error)
}
});
return div;
}
item.php file
<?php
include_once '../datatables_ajax/conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();
$idsol = $_POST['idsol'];
$consulta = "CALL Items('".$idsol."')";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
//print json_encode($data, JSON_UNESCAPED_UNICODE);
echo '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;"><tbody>';
foreach(['ID','item','number'] as $attribute) {
echo '<tr><th>'.$attribute.'</th>';
foreach($data as $row) {
echo '<td>'.$row[$attribute].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
$conexion=null;
?>
items.php returns id_sol, item_name, item_number I wanted to return it first as text(it works if you only open the file) but the table just stay in "Loading..." when trying to show it, also it would be helpful if someone help me to return that data as a table.
First
you should remove the loading text when the ajax call is complete that's inside the complete: function(){} not inside the success: function(){}.
Second
you can return the data as a table from PHP like this:
if ($resultado->rowCount()){ //meaning if the request returned some data
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
$d = [];
$i = ;
foreach($data as $val){
$d[i]['fieldName'] = $val['columnName'];
}
echo json_encode($data);
}else{ //no data returned
//error handling here
}
Third
if you want to return the data as an HTML table then do this:
if ($resultado->rowCount()){ //meaning if the request returned some data
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
$output = "
<table>
<thead>
<tr>
<th>first header </th>
<th>second header </th>
</tr>
</thead>
<body>
";
$d = [];
$i = ;
foreach($data as $val){
$output .="
<tr>
<td>first header data=".$val[columnName]."</td>
<td>second header data=".$val[columnName]."</td>
</tr>";
$d[i]['fieldName'] = $val['columnName'];
}
$output .=" </tbody>
</table>";
echo json_encode($output);
}else{ //no data returned
//error handling here
}
Currently i am working on eCommerce website in that i have to display all data from database to datatable. Data is coming properly in datatable but searching, sorting and pagination is not working.If any body know solution than please help. Below is my code
Controller.php
Public function transaction_data()
{
$id = $this->session->Vendordetail['id'];
$transactionData = $this->Mdl_vendor_payment->get_order_list($id);
$requestData= $_REQUEST;
$totalData = count($transactionData);
$totalFiltered = count($transactionData);
$return_days = $this->Mdl_common->get_setting('shipping_charge');
foreach($transactionData as $transaction){
$product = $this->Mdl_common->product_id($transaction['prodouct_id']);
$data['order_id'] = $transaction['order_id'];
$data['created'] = $transaction['created'];
if($transaction['status'] == 5){
$data['status'] = '<h5><span class="label label-danger">Cancelled</span></h5>';
}else if($transaction['status'] == 4){
$data['status'] = '<h5><span class="label label-default">Return</span></h5>';
}else if($transaction['status'] == 3){
$data['status'] = '<h5><span class="label label-success">Success</span></h5>';
}else if($transaction['status'] == 2){
$data['status'] = '<h5><span class="label label-primary">Dispatch</span></h5>';
}else if($transaction['status'] == 1){
$data['status'] = '<h5><span class="label label-primary">Ready To Dispatch</span></h5>';
}else{
$data['status'] = '<h5><span class="label label-primary">Approve</span></h5>';
}
$data['price'] = '<i class="fa fa-rupee"></i> '.$transaction['price']*$transaction['qty'];
$data['settlement_price'] = '<i class="fa fa-rupee"></i> '.$transaction['settlement_price']*$transaction['qty'];
$shipping_charge = $return_days['value'] * ($transaction['qty'] * $product['weight']);
$data['shipping_charge'] = '<i class="fa fa-rupee"></i> '.$shipping_charge;
$data['commission_fee'] = ($transaction['price']*$transaction['qty'])-($transaction['settlement_price']-$transaction['qty']);
$data['payable_amount'] = ($transaction['settlement_price']*$transaction['qty'])-$shipping_charge;
$data['order'] = $transaction;
$data['product'] = $product;
$assignment_datas[] = $data;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $assignment_datas
);
echo json_encode($json_data);
die;
}
Below is the code for view file
View.php
$(document).ready(function() {
var dt = $('#datatable_example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url":"<?php echo base_url(); ?>index.php/Vendor_payment/transaction_data",
"type":"POST",
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "order_id" },
{ "data": "created" },
{ "data": "status" },
{ "data": "price" },
{ "data": "settlement_price" },
{ "data": "shipping_charge" }
],
"order": [[0, 'asc']]
} );
// Array to track the ids of the details displayed rows
var detailRows = [];
$('#datatable_example tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dt.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
// Remove from the 'open' array
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
// Add to the 'open' array
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
// On each draw, loop over the `detailRows` array and show any child rows
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
This code is work fine for me...
In view page:
<table id="user_datatable" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 5%;">ID</th>
<th>Client name</th>
<th>Mobile</th>
<th>Email</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#user_datatable').DataTable({
'pageLength': 1,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url': '<?php echo base_url(); ?>user/userList'
},
'columns': [{
data: 'id'
},
{
data: 'name'
},
{
data: 'mobile'
},
{
data: 'email'
},
{
data: 'action'
},
]
});
});
</script>
In Controller page
public function userList() {
$postData = $this->input->post();
$data = $this->Data_model->getUserList($postData);
echo json_encode($data);
}
In Model page
Set the table name in $table variable
// $table = 'clients';
Add column name whatever you add in datatable
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
function getUserList($postData=null) {
$response = array();
$table_name = 'clients';
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$searchQuery = "";
if($searchValue != ''){
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$this->db->select('count(*) as allcount');
$records = $this->db->get($table_name)->row();
$totalRecords = $records->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchValue != '')
$this->db->where($searchQuery);
$records = $this->db->get($table_name)->row();
$totalRecordwithFilter = $records->allcount;
## Fetch records
$this->db->select('*');
if($searchValue != '')
$this->db->where($searchQuery);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$records = $this->db->get($table_name)->result();
$data = array();
foreach($records as $key => $record) {
$data[] = array(
"id"=> ($key + 1),
"name"=>$record->name,
"mobile"=>$record->mobile,
"email"=>$record->email,
"action"=>"<a href='".base_url()."user/update/".$record->id."' type='button' class='btn btn-success'>Update</a><a href='".base_url()."user/delete/".$record->id."' type='button' class='btn btn-danger' style='margin-left: 5px;'>Delete</a>",
);
}
## Response
$response = array(
"draw" => intval($draw),
"recordsTotal" => $totalRecordwithFilter,
"recordsFiltered" => $totalRecords,
"data" => $data
);
return $response;
}
I'm trying to incorporate the jquery sortable functionality into my website and saving the positions in the database is giving me all sorts of headaches... I've been fighting this for 3 days now, and I cannot seem to get this work properly.
As it stands, it is saving positions to the database, but not in the order or positions, that you'd expect. Meaning, if I move the item in position 0 to position 1, it saves the positions in a different order in the db. check out a live version here.
Here is my code...
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while($items = $result->fetch_assoc()) {
?>
<div id='sort_<?php echo$items['position'] ?>' class='items'>
<span>☰</span> <?php echo$items['description'] ?>
</div>
<?php
}
}
?>
</div>
js.js file:
$("#container").sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: {positions: post, id: itId },
dataType: 'json',
cache: false,
success: function(output) {
// console.log('success -> ' + output);
},
error: function(output) {
// console.log('fail -> ' + output);
}
});
}
});
$("#container").disableSelection();
save.php file:
require_once('conn.php');
$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);
$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);
foreach($arr['sort'] as $a) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$a'
WHERE id = '{$row['id']}' ";
mysqli_query($db, $sql);
}
echo json_encode( ($arr['sort']) );
Can anyone please point to where I am going wrong on this?
Thank you in advance.
Serge
In case someone lands on here, here is what worked in my case...
NOTE: I did not create prepared statements in the index.php select function. But you probably should.
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<div id='sort_<?php echo $items['id'] ?>' class='items'>
<span>☰</span> <?php echo $items['description'] ?>
</div>
<?php
}
}
?>
</div>
jquery sortable file:
var ul_sortable = $('#container');
ul_sortable.sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = ul_sortable.sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
ul_sortable.disableSelection();
update php file:
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
require_once('conn.php');
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$db->close();
}
Change your JS code like this:
{...}
tolerance: 'pointer',
cursor: 'move',
// new LINE
items: '.items', // <---- this is the new line
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize'); // it could be removed
// new LINES start
var post={},count=0;
$(this).children('.items').each(function(){
post[++count]=$(this).attr('id');
});
// new LINES end
$.ajax({
{...}
With this $.each loop you overwrite your var post -> serialize and define your own sort order. Now look at your $_POST["positions"] with PHP print_r($_POST["positions"]); and you have your positions in your own order.
I would like to ask a question and I need a little help from you guys.
I would like to use jquery Datatable plugin in my project but something going wrong.
The table is displayed properly, but none of the datatable functions working.
Here is my code:
function get_answer(get_date, get_id) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var date = get_date;
var id = get_id;
var data = {
'action': 'get_answers_ajax',
'date': date,
'id': id
};
var table_structure = '<table id="result-' + id + '" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#tabs-' + id).append(table_structure);
jQuery.post(ajaxurl, data, function (response) {
if (response) {
var obj = JSON.parse(response);
var heads = [];
var results = [];
jQuery.each(obj, function (key, res) {
if (jQuery.inArray(res.label, heads) == '-1')
{
heads.push(res.label);
}
results.push(res.value);
});
var head = jQuery('#tabs-' + id + ' .result_head tr');
head.empty();
jQuery.each(heads, function (key, value) {
head.append('<th>' + value + '</th>');
});
var body = jQuery('#tabs-' + id + ' .result_body');
body.empty();
if (results.length > 0) {
body.append('<tr role="row" class="odd">'); // Open tr
var count_heads = heads.length;
var count_answ = 0;
jQuery.each(results, function (key, value) {
if (value.substring(0, 4) == 'http') {
body.find('tr').last().append('<td><img src="' + value + '" alt="none" width="200px" height="200px" /></td>');
} else {
body.find('tr').last().append('<td>' + value + '</td>');
}
count_answ++;
if ((count_answ % count_heads) == 0) {
body.find('tr').last().find('td').last().after('</tr>');
body.find('tr').last().after('<tr role="row" class="even">');
}
});
body.find('tr').last().after('</tr>'); // Close tr
}
}
});
jQuery('#result-' + id).dataTable(
{
"ordering": true,
"searching": true
}
);
The heads and the reults array looks like this:
Heads => ["Eredmény", "Felhasználó", "Dátum"]
Results => ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"]
My PHP function which one gives back the data is this:
function get_answers() {
global $wpdb;
$date = $_POST['date'];
$form_id = $_POST['id'];
$date_pice = explode(' - ', $date);
$question = array();
$answer = array();
$sql_answers = "SELECT lead.date_created, detail.field_number, detail.value, detail.form_id, meta.display_meta FROM wp_rg_lead_detail AS detail INNER JOIN wp_rg_lead AS lead ON detail.lead_id = lead.id INNER JOIN wp_rg_form_meta AS meta ON detail.form_id = meta.form_id WHERE lead.date_created BETWEEN '{$date_pice[0]}' AND '{$date_pice[1]}' AND detail.form_id = '{$form_id}' ";
$answers = $wpdb->get_results($sql_answers);
foreach ($answers as $ans_info) {
$meta = self::bsp_unserialize($ans_info->display_meta);
foreach ($meta[fields] as $fields) {
if ($fields["id"] == $ans_info->field_number) {
$question["kerdes"] = $fields["label"];
$answer["valasz"] = $ans_info->value;
}
}
$toJSON[] = array("label" => $question["kerdes"], "value" => $answer["valasz"]);
}
echo json_encode($toJSON);
die();
}
So, the table shows all of the data in it, but If i would like to search or ordering or paginating nothings works.
Any hint about it?
Thx a lot
I could solve the problem.
I just modifed the append method, and now I making a html string with the ready html element and I jut append that at the end of the process.
jQuery(document).ready(function () {
var table_structure = '<table id="result" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#table').append(table_structure);
var heads = ["Result", "User", "Date"];
var results = ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"];
jQuery('.result_head tr').empty();
jQuery.each(heads, function (key, value) {
jQuery('.result_head tr').append('<th>' + value + '</th>');
});
var body = jQuery('.result_body');
body.empty();
if (results.length > 0) {
var count_heads = heads.length;
var count_answ = 0;
var html = "";
jQuery.each(results, function (key, value) {
if ((count_answ % count_heads) === 0) {
html += '<tr>';
}
if (value.substring(0, 4) == 'http') {
html += '<td><img src="' + value + '" alt="none" width="200px" height="200px"/></td>';
} else {
html += '<td>' + value + '</td>';
}
count_answ++;
if ((count_answ % count_heads) === 0) {
html += '</tr>';
body.append(html);
html = '';
}
});
}
jQuery('#result').dataTable(
{
"ordering": true,
"searching": true
}
);
});
In this below code when i update without checking any value it displays all the values from db.And error Undefined variable: records and Invalid argument supplied for foreach() at 113 and 119
Undefined variable: row in line 123
Trying to get property of non-object in 123in student_detail_view.
Please any one help me.
Controller student_site:
function index()
{
$data = array();
if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}
$this->load->view('student_view', $data);
}
function studentupdate()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}
if($query = $this->student_model->get_records($exam_name))
{
$data['records'] = $query;
}
if($query = $this->student_model->get_course_code_records($exam_name))
{
$data['course_records'] = $query;
}
if($query = $this->student_model->get_all_coursesubject_records())
{
$data['all_coursesubject_records'] = $query;
}
$this->load->view('student_detail_view', $data);
}
function studentcreate()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$data['exam_name'] = $exam_name;
/*if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}*/
if($query = $this->student_model->get_course_code_records($exam_name)) //get unique records of coursecode from the coursesubject table
{
$data['course_records'] = $query;
}
/*if($query = $this->student_model->get_subject_code_records($exam_name)) //write seperate function to get the the subject codes frm the coursesubject table based on the selected course code.
{
$data['subject_records'] = $query;
} */
$this->load->view('student_update', $data);
}
function subject_records()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_subject_records($exam_name,$course_name))
{
$data['subject_records'] = $query;
}
$this->load->view('subject_view', $data);
}
function create_student()
{
/*$data = $this->input->post();
print_r($data);
var_dump($this->input->post());
$data=$this->input->post();*/
$j=1;
$createstudent = $this->input->post('createstudent');
if( $this->input->post('createstudent') != false ){
foreach($createstudent as $row_id)
{
$this->form_validation->set_rules("register_number_" . $row_id, "Register No", "required|min_length[2]");
//$this->form_validation->set_rules("name_". $row_id,"`Name`","required|xss_clean|min_length[1]");
}
}
if ($this->form_validation->run() == FALSE){
$data["message"]="";
$this->load->view("student_detail_view",$data);
//$this->load->view("master_data/view_master_data_footer");
}
while($j<=$this->uri->segment(3))
{
$data = array(
'exam_name' => $this->input->post('exam_name'),
'register_number' => $this->input->post('register_number_'.$j),
'name' => $this->input->post('name_'.$j),
'course_code' => $this->input->post('course_name_id'.$j),
'subject_code' => $this->input->post('subject_name'),
);
// $exam_name = mysql_real_escape_string($_POST["exam_name_id".$j]);//
$register_number=$this->input->post('register_number_'.$j);
if ($register_number != "")
{
$this->student_model->add_record($data);
}
$j++;
}
redirect('student_site', 'refresh');
}
function delete()
{
$this->student_model->delete_row();
redirect('student_site', 'refresh');
}
function manage_student()
{
$data['title']="Manage Student";
//query model to get data results for form
$data=array();
if($query=$this->student_model->get_student_records()){
$data['records']=$query;
}
$editstudent = $this->input->post('editstudent');
if( $this->input->post('editstudent') != false ){
foreach($editstudent as $row_id)
{
$this->form_validation->set_rules("register_number_" . $row_id, "register_number", "required|min_length[2]");
}
}
if ($this->form_validation->run() == FALSE){
$data["message"]="";
//$this->load->view("master_data/view_master_data_header",$data);
//$this->load->view("master_data/view_master_data_nav");
$this->load->view("student_detail_view",$data);
//$this->load->view("master_data/view_master_data_footer");
} else {
// single update - working
if( $this->input->post('editstudent') != false )
{
foreach ($editstudent as $row_id)
{
$data = array(
'register_number' => $this->input->post('register_number_'.$row_id),
'name' => $this->input->post('name_'.$row_id),
'course_code' => $this->input->post('course_code_id'.$row_id),
'subject_code' => $this->input->post('subject_code_id'.$row_id),
);
$this->student_model->update_student_records( $row_id, $data );
}
$this->session->set_flashdata('dbaction', 'Selected Records have been updated successfully');
redirect('student_site', 'refresh');
}
}
}
$data = array(
'exam_name' => $this->input->post('exam_name_id'),
'register_number' => $this->input->post('register_number'),
'name' => $this->input->post('name'),
'subject_code' => $this->input->post('subject_code'),
'course_code' => $this->input->post('course_code'),
);
$exam_name = $this->input->post('exam_name');
$register_number = $this->input->post('register_number');
$name = $this->input->post('name');
$course_code = $this->input->post('course_code');
$subject_code = $this->input->post('subject_code');
$this->student_model->update_student_record($exam_name,$register_number,$name,$course_code,$subject_code,$data);
$data = array();
$query = $this->student_model->get_records($exam_name);
echo "<pre>";
print_r($query);
exit;
if($query)
{
$data['records'] = $query;
}
$this->load->view('student_detail_view', $data);
function crud()
{
}
function deleting()
{
}
model:student_model
function get_records($exam_name)
{
$this->db->where('exam_name',$exam_name);
$query = $this->db->get('student_table');
return $query->result();
}
function get_exam_data()
{
$this->db->distinct();
$this->db->select("CONCAT(exam_name, ' ', month,' ',year) AS fullexamname", FALSE);//this will concat the value
$query = $this->db->get('exam_table');
return $query->result();
}
function get_course_records($exam_name)
{
//echo "exam_name".$exam_name;
$this->db->select('exam_name,course_code');
$this->db->where('exam_name',$exam_name);
$query = $this->db->get('student_table');
return $query->result();
}
function get_subject_records($exam_name,$course_name)
{
//echo "exam_name inside get_subject_records".$exam_name;
$this->db->select('subject_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_all_coursesubject_records()
{
//echo "exam_name inside get_subject_records".$exam_name;
$this->db->select('course_code');
$this->db->select('subject_code');
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_course_code_records($course_name)
{
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_subject_code_records()
{
$this->db->distinct();
$this->db->select('subject_code');
$query = $this->db->get('coursesubject');
return $query->result();
}
function update_student_record($exam_name,$register_number,$name,$course_code, $subject_code,$data)
{
echo "exam_name".$exam_name;
echo "register_number".$register_number;
echo "name".$name;
$this->db->where('exam_name',$exam_name);
$this->db->where('register_number',$register_number);
//$this->db->where('name',$name);
//$this->db->where('course_code',$course_code);
//$this->db->where('subject_code',$subject_code);
$this->db->update('student_table',$data);
}
view :student_detail_view
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.dataTables.js" ></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.dataTables.min.js" ></script>
<section id="tables">
<script>
jQuery(document).ready(function() {
oTable = jQuery('#studenttable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
</script>
<script type="text/javascript" charset="utf-8">
function get_studentdetails() {
var exam_name = jQuery('#exam_name_id').val();
//alert("exam_name"+exam_name);
jQuery.ajax({
data: {
exam_name: exam_name,
},
type: 'POST',
url: 'student_site/studentupdate',
success: function(data){
//alert("inside change");
console.log(data);
jQuery('#details').html(data);
jquery('#deleting').html(data);
}
});
jQuery(document).ready(function(){
jQuery.ajax({
data: {
exam_name: exam_name,
},
type: 'POST',
url: 'student_site/studentcreate',
success: function(data){
//alert("inside change");
console.log(data);
jQuery('#crud').html(data);
jquery('#deleting').html(data);
}
});
});
}
function CheckBoxVerification(From)
{
alert('hai');
alert('hai:' $("table input[type=checkbox]:checked").length);
if(From == "Insert")
{
if(!!$('#rowInsert input:checked').length == false)
{
alert('please select at least one check box to Create ...!');
}
}
if(From == "Update")
{
if(!!$('#rowUpdate input:checked').length == false)
{
alert('please select at least one check box to Update ...!');
}
}
}
function get_subjectdetails() {
//var index = jQuery('#index').val();
var course_name = jQuery('#course_name_id').val();
//alert("course_name"+course_name);
//var exam_name = jQuery('#course_name_id>option:selected').text();
var exam_name = jQuery('#exam_name_id').val();
var ssubject_code = jQuery('#ssubject_code_id').val();
//var partsArray = exam_name.split('.');
//alert("ssubject_code"+ssubject_code);
//alert("course_name"+course_name);
//alert("exam_name"+exam_name);
jQuery.ajax({
data: 'exam_name='+exam_name+'&course_name=' + course_name,
type: 'POST',
url: 'student_site/subject_records',
success: function(data){
//alert("inside change");
console.log(data);
//alert ("data"+data);
//for(var j = course_name; j < ssubject_code; j++)
//{
jQuery('#ssubject_code').empty().append(data);
//}
}
});
}
</script>
<?php
$attributes=array(
'name'=>'updatecustomer',
'id'=>'updatecustomer'
);
echo form_open('student_site/manage_student',$attributes);
?>
<div id="validation_failed">
<?php
echo validation_errors();
?>
<?php $data = array();
foreach ($records as $row)
{
$data[$row->course_code] = $row->course_code;
}
$subject_data = array();
foreach ($records as $row)
{
$subject_data[$row->subject_code] = $row->subject_code;
}
var_dump($row->course_code );
?>
<div id="Processy">
<table class="display table table-bordered table-striped" id='studenttable'>
<thead>
<tr font style='font-size:13px'>
<th> </th>
<th> </th>
<th>Register Number</th>
<th>Name </th>
<th>Course Code</th>
<th>Subject Code</th>
</tr></thead>
<?php if(isset($records)) : foreach($records as $row) : ?>
<tr >
<td>
<?php echo anchor('student_site/delete/'.$row->id, 'Delete',array('onClick'=>"return confirm('Are you sure want to delete..?')")); ?>
</td>
<td id="rowUpdate">
<input type=checkbox name="editstudent[]" id="editstudent[]" value="<?php echo $row->id ?>">
</td>
<td ><input class="inputmedium span2" type="text" name="register_number_<?php echo $row->id ?>" id="register_number_<?php echo $row->id ?>" value="<?php echo $row->register_number; ?>" ></td>
<td ><input class="inputmedium span2" type="text" name="name_<?php echo $row->id ?>" id="name_<?php echo $row->id ?>" value="<?php echo $row->name; ?>" ></td>
<td >
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" onChange="get_subjectdetails()" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<?php
$js = 'class="dropdown_class" id="subject_code_id'.$row->id.'"';
$js_name = 'subject_code_id'.$row->id;
echo form_dropdown($js_name, $subject_data, $row->subject_code, $js);
?>
<div id="ssubject_code" ></div>
<input type="hidden" name="ssubject_code" id="ssubject_code" value="ssubject_code"/>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<center>
<br /><input type="submit" class="btn-success btn" value="Update Student"></center>
<?php else : ?>
<h2>No records were returned.</h2>
<?php endif; ?>
you should check if $record is set and then use foreach.
Try something like:
if(isset($records)){
foreach($records as $row){
//do things here
}
}
Try echo on the records you get from the query as follows:
function update()
{
$data = array(
'exam_name' => $this->input->post('exam_name_id'),
'register_number' => $this->input->post('register_number'),
'name' => $this->input->post('name'),
'subject_code' => $this->input->post('subject_code'),
'course_code' => $this->input->post('course_code'),
);
$exam_name = $this->input->post('exam_name');
$register_number = $this->input->post('register_number');
$name = $this->input->post('name');
$course_code = $this->input->post('course_code');
$subject_code = $this->input->post('subject_code');
$this->student_model->update_student_record($exam_name,$register_number,$name,$course_code,$subject_code,$data);
$data = array();
$query = $this->student_model->get_records($exam_name);
echo "<pre>";
print_r($query);
exit;
if($query)
{
$data['records'] = $query;
}
$this->load->view('student_detail_view', $data);
}