I want to store datatables data inside an array or json format and use it to pass to php for FPDF use. In my datatable I created a custom button named "PDF", when the button is click I want to store the data and pass it into php via post. I have this code, but it wont work if I put ajax inside the action function of the custom button I made. It doesnt go to the url I declared. Here's the code:
EDITED
<script>
$(document).ready(function() {
var table = $('#stud_list').DataTable({
dom: 'Blfrtip',
columnDefs: [{
targets: 1,
className: 'noVis'
}],
buttons: [{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csvHtml5',
exportOptions: {
columns: ':visible'
}
},
{
text: 'PDF',
exportOptions: {
columns: ':visible'
},
action: function(e, dt, node, config) {
$.ajax({
url: 'pdfViewStudent.php',
type: 'post',
data: table.row().data().toArray(),
dataType: 'json',
success: function(returnedData) {
console.log(returnedData);
}
});
}
},
'colvis'
],
columnDefs: [{
targets: -1,
visible: false
}],
initComplete: function() {
this.api().columns([4, 5, 6]).every(function() {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function() {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
});
</script>
I edited the code, the error was gone but nothing happens also.
ADDED HTML CODE:
<table id="stud_list" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>First Name</th>
<th>Initials</th>
<th>Grade</th>
<th>Section</th>
<th>Gender</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$result = mysqli_query($connect, "SELECT * FROM tbl_student") or die(mysqli_error());
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
?>
<tr>
<td>
<?php echo $row['student_id']; ?>
</td>
<td>
<?php echo $row['last_name']; ?>
</td>
<td>
<?php echo $row['first_name']; ?>
</td>
<td>
<?php echo $row['Initials']; ?>
</td>
<td>
<?php echo $row['gradeLevel_id']; ?>
</td>
<td>
<?php echo $row['section_id']; ?>
</td>
<td>
<?php echo $row['gender']; ?>
</td>
<td>
<a class="btn btn-success btn-xs" href="studentProfile.php?studId=<?php echo $row['student_id']; ?>"><i class="fa fa-eye fa-1x"></i></a>
<button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#editStudent" data-studaydi="<?php echo $row['student_id']; ?>" data-cardaydi="<?php echo $row['card_id']; ?>" data-seksyon="<?php echo $row['section_id']; ?>" data-gardyan="<?php echo $row['Parents_No']; ?>" data-location="<?php echo $row['address']; ?>" data-ln="<?php echo $row['last_name']; ?>" data-fn="<?php echo $row['first_name']; ?>" data-mn="<?php echo $row['Initials']; ?>" data-gn="<?php echo $row['gender']; ?>" data-cy="<?php echo $row['cyear']; ?>" data-gr="<?php echo $row['gradeLevel_id']; ?>"><i class="fa fa-edit fa-1x"></i></button>
<a onclick="javascript: return confirm('DO YOU REALLY WANT TO DELETE THIS STUDENT?');" href="removeStudent.php?id=<?php echo $row['student_id']; ?>" class="btn btn-danger btn-xs"><i class="fa fa-remove fa-1x"></i></a>
</td>
<?php } ?>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
Related
On some of my datatables doesn't show the sorting and search. The red boxes is what I want to display but I cant get them showing u on some of my tables. The datatables are exactly the same, I've copied the code but nothing changed. So I'm asking if someone has a solution for me?
Below you will see some of my javascript and html code:
--- javascript ---
$("#dataTablesFull, #dataTablesFull2, #dataTablesFull3, #dataTablesFull4").dataTable( {
"pageLength": <?php echo getConfigValue("table_records"); ?>,
"dom": '<"top"f>rt<"bottom"><"row dt-margin"<"col-md-6"i><"col-md-6"p><"col-md-12"B>><"clear">',
"buttons": [ 'copy', 'csv', 'excel', 'pdf', 'print' ],
"stateSave": true,
"fixedHeader": false,
"oLanguage": {
"sSearch": "",
"sEmptyTable": "<?php _e('Oops! Er is niets om weer te geven.'); ?>",
"sZeroRecords": "<?php _e('Niets gevonden'); ?>",
"sInfo": "<?php _e('Weergeven van: '); ?> _START_ <?php _e('tot'); ?> _END_ <?php _e('van'); ?> _TOTAL_ <?php _e('records.'); ?>",
"sInfoEmpty": "",
"oPaginate": {
"sNext": "<?php _e('Volgende'); ?>",
"sPrevious": "<?php _e('Vorige'); ?>",
"sFirst": "<?php _e('Eerste pagina'); ?>",
"sLast": "<?php _e('Laatste pagina'); ?>"
}
},
"columnDefs": [ { "orderable": false, "targets": -1 } ] }
);
--- html ---
<div class="table-responsive">
<table id="dataTablesFull" class="table table-striped">
<thead>
<tr>
<th>Naam</th>
<th>E-mail</th>
<th>Antwoord</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($contacts as $contact) { ?>
<tr>
<td>
<?php echo $name; ?>
</td>
<td>
<?php echo $email; ?>
</td>
<td>
<?php
if(empty($answer)) {
echo " -";
}
if(!empty($answer)) {
echo $answer;
}
?>
</td>
<td>
<?php
if($contact['status'] == 0) {
echo "Verzonden";
}
if($contact['status'] == 1) {
echo "Beantwoord";
}
?>
</td>
<td>
<div class='pull-right btn-group'>
<a href="#" onClick='#' class='btn btn-info btn-flat btn-sm'><i class='fa fa-eye'></i></a>
<a href="#" onClick='#' class='btn btn-danger btn-flat btn-sm'><i class='fa fa-trash-o'></i></a>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
For the buttons to appear you need "B" on the "dom" option (i.e. Buttons)
For the search bar to appear you need "f" in the "dom" option (i.e. filter)
For pagination you need "p" in the "dom" option. (i.e. pagination)
i.e.
$('#myTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
]
} );
Refer to https://datatables.net/reference/option/dom and https://datatables.net/extensions/buttons/
You seem to have them there but with extra styling applied, it could it be the case that the stylesheet that is being referred to is not loading (check via browser dev tools)
I have a table which i make the td's contenteditable, for the user to easily input the data needed.
Every rows and td have value of null in database. It will have value when the user will input something and it will save/update when button save is click
my php for tbody :
<?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var= $_SESSION["username"] ;
try {
$pdo = new PDO('mysql:host=localhost:3306;dbname=******;', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare(
" SELECT * from tbl_assessment WHERE employeeName = '{$_SESSION['emp_name']}' "
);
$flag = $stmt->execute();
if ( !$flag ) {
$info = $stmt->errorInfo();
exit( $info[2] );
}
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
#$tbody1 .='<tr>';
$tbody1 .=' <input type="hidden" id="id" value="'.$_SESSION['id'].'"/> ';
$tbody1 .=' <input type="hidden" id="emp_name" value="'.$_SESSION['emp_name'].'"/> ';
$tbody1 .=' <input type="hidden" id="teamCode" value="'.$_SESSION['teamCode'].'"/> ';
$tbody1 .=' <input type="hidden" id="sectionCode" value="'.$_SESSION['sectionCode'].'"/> ';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["date"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["staffName"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["findings"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["action"].'</td>';
$tbody1 .='<td style="height:30px" contenteditable>'.$row["date_accomplished"].'</td>';
$tbody1 .='<td><button class="btn btn-warning px-2" id="btnSaveFindings" style="color:black;font-weight:bold;" title="Save"><i class="fas fa-save" aria-hidden="true"></i></button><button class="btn btn-info px-2" id="btnEdit" style="color:black;font-weight:bold;" title="Edit"><i class="fas fa-edit" aria-hidden="true"></i></button></td>';
#$tbody .='</tr>';
}
}
catch ( PDOException $e ) {
echo $e->getMessage();
$pdo = null;
}
?>
my html for table :
<div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
<div class="" style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
<button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
<table class="assessment" id="assessment" width="1526px" >
<thead style="background:-moz-linear-gradient( white, gray);">
<tr>
<th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
</tr>
<tr> <!---FIRST TABLE ROW--->
<th>DATE</th>
<th>NAME OF THE STAFF/S</th>
<th>ASSESSMENT/FINDINGS</th>
<th>ACTION TAKEN</th>
<th>DATE ACCOMPLISHED</th>
<th>ACTION</th>
</tr>
<tbody>
<?php echo $tbody1; ?>
</tbody>
</thead>
</table><br><br>
</div>
what would be the function of btnSaveFindings to update the value of td in database?
A few things to note,
Your query is not using a prepared statement - which is very simple with PDO; suggest you use that!
Your loop can generate multiple HTML elements with the same ID - this violates the uniqueness of an ID - if something can have the same ID, it can probably be a class instead.
When printing large blocks of HTML, its often better to exit PHP mode to print it where you need it.
To update the table, use jQuery with AJAX - assign classes to the different <td> elements, so we can fetch them with jQuery, and when you click the button, find the closest values of that row. Add a rows unique identifier to a data-* attribute of the button, so we know which row to update.
<?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var = $_SESSION["username"] ;
try {
$pdo = new PDO('mysql:host=localhost:3306;dbname=******;charset=utf8mb4', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare("SELECT * FROM tbl_assessment WHERE employeeName = :employeeName");
$stmt->execute(['employeeName' => $_SESSION['emp_name']]);
?>
<script>
$(".btnSaveFindings").on("click", function() {
var id = $(this).data('assessment-id'),
row = $(this).closest("tr"),
date = $(row).find('.assessment-date')[0],
staffname = $(row).find('.assessment-staffname')[0],
findings = $(row).find('.assessment-findings')[0],
action = $(row).find('.assessment-action')[0],
accomplished = $(row).find('.assessment-date-accomplished')[0];
$.ajax({
type: "POST",
url: "updateRow.php",
data: {id: id,
date: date,
staffname: staffname,
findings: findings,
action: action,
accomplished: accomplished},
success: function(data) {
var status = data.status,
message = data.message;
alert(message);
}
});
});
</script>
<div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
<div class="" style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
<button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
<table class="assessment" id="assessment" width="1526px" >
<thead style="background:-moz-linear-gradient( white, gray);">
<tr>
<th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
</tr>
<tr> <!---FIRST TABLE ROW--->
<th>DATE</th>
<th>NAME OF THE STAFF/S</th>
<th>ASSESSMENT/FINDINGS</th>
<th>ACTION TAKEN</th>
<th>DATE ACCOMPLISHED</th>
<th>ACTION</th>
</tr>
<tbody>
<?php
while ($row = $stmt->fetch()) { ?>
<tr>
<td style="height:30px" class="assessment-date" contenteditable><?php echo $row["date"] ?></td>
<td style="height:30px" class="assessment-staffname" contenteditable><?php echo $row["staffName"]; ?></td>
<td style="height:30px" class="assessment-findings" contenteditable><?php echo $row["findings"]; ?></td>
<td style="height:30px" class="assessment-action" contenteditable><?php echo $row["action"]; ?></td>
<td style="height:30px" class="assessment-date-accomplished" contenteditable><?php echo $row["date_accomplished"]; ?></td>
<td>
<button class="btn btn-warning px-2 btnSaveFindings" style="color:black;font-weight:bold;" title="Save" data-assessment-id="<?php echo $row['id']; ?>">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
<button class="btn btn-info px-2 btnEdit" style="color:black;font-weight:bold;" title="Edit">
<i class="fas fa-edit" aria-hidden="true"></i>
</button>
</td>
</tr>
<?php
}
?>
</tbody>
</thead>
</table>
<br />
<br />
</div>
<?php
} catch(PDOException $e) {
error_log($e->getMessage());
echo "An error occurred";
}
Then you need to create the file updateRow.php that runs the query.
<?php
header('Content-Type: application/json');
$pdo = new PDO('mysql:host=localhost:3306;dbname=******;charset=utf8mb4', '****', '*****' );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// See that the POST is sent
if (empty($_POST)) {
echo json_encode(['status' = false, 'message' => 'No data was sent. Update aborted']);
exit;
}
try {
$stmt = $pdo->prepare("UPDATE tbl_assessment
SET date = :date,
staffName = :staffName,
findings = :findings,
action = :action,
date_accomplished = :date_accomplished
WHERE id = :id");
$stmt->execute(['date' => $_POST['date'],
'staffName' => $_POST['staffName'],
'findings ' => $_POST['findings'],
'action ' => $_POST['action'],
'date_accomplished ' => $_POST['date_accomplished'],
'id ' => $_POST['id']]);
echo json_encode(['status' = true, 'message' => 'Update completed.']);
} catch (PDOException $e) {
error_log($e->getMessage());
echo json_encode(['status' = false, 'message' => 'An error occurred. Update failed.']);
}
As a final note, its often way better to use CSS classes on elements instead of inline styling. Makes for cleaner code, and more repeatable code.
I am trying to delete the table entry without opening the .php file using jQuery post.
The whole thing works without problems when I just use the usual html post form.
The alert(data) does not trigger, it only adds ".../?player_id_del=1" or whatever ID click into the URL.
What am I doing wrong?
Here is some of my index.php, i get the whole data from a database:
<table class = "table table-hover">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr>
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<form id="del-form">
<div>
<input type="number" id="player_id_del" name="player_id_del" value="<?php echo htmlspecialchars($player["PLAYER_ID"]); ?>" />
</div>
<div>
<button type="submit" id="submit-btn" class="btn btn-danger">Delete</button>
</div>
</form>
<script>
$("#submit-btn").click(function(){
$.post("deletePlayer.php", $("#del-form").serialize() , function(data) {
alert(data);
});
});
</script>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
Here is my deletePlayer.php:
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
echo "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
echo "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
?>
Thank You in advance for any help!
By default jQuery's click event reload the document so, you should try using,
$("#submit-btn").click(function(e){
e.preventDefault();
e.stopPropagation();
});
Also instead of $.post, try using $.ajax
There are many issues in your code
E.g IDs for form and delete input button are repeating (id of element should not be same it should be unique),
The following code is the tested and working.
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
$response = array();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
$response["success"] = 1;
$response["id"] = $player_id;
$response["message"] = "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
$response["success"] = 0;
$response["message"]= "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
echo json_encode($response);
?>
<table class = "table table-hover" id="mPlayersTabel">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr id= "<? echo $player["PLAYER_ID"]; ?>">
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<div>
<button type="submit" player-id="<? echo $player["PLAYER_ID"]; ?>" class="btn btn-danger" >Delete</button>
</div>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".btn-danger").on("click touchend" , function(){
var id = $(this).attr("player-id");
$.ajax({
url: 'deletePlayer.php',
type: 'POST',
data: {
player_id_del: id
},
dataType: 'json',
success: function (response) {
//Add this line and try
response = JSON.parse(JSON.stringify(response));
alert(response['message']);
switch (response['success']) {
case 1:
$("#mPlayer" + response['id']).remove();
break;
}
}
});
});
});
</script>
I have the following code to add, edit and delete user. Add function works fine but edit and delete functions are not working. I'm not sure where it goes wrong.
application/view/userlist.php
<script type="text/javascript">
var oTable;
$(document).ready(function()
{
oTable = $('#userListTable').dataTable( {
"iDisplayLength": 25,
"aLengthMenu": [5,10,25,50,100],
"aoColumns": [ {
"bSortable": false },
null,
null,
null,
null,
null,
null,
null,
null, {
"bSortable": false } ]
});
oTable.fnSort( [ [1,'asc'] ] );
});
function removeUser()
{
var ids = '';
$("input:checked", oTable.fnGetNodes()).each(function(){
if (ids == '') {
ids += $(this).val();
}else{
ids += ','+$(this).val();
}
});
var url = "<?php echo base_url(); ?>Admin/userRemove/";
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="ids" value="' + ids + '" />' +
'</form>');
console.log(form);
$('body').append(form);
if (ids != '') {
form.submit();
}else{
alert('Select user to remove');
}
}
</script>
//some codes here
<button type="button" data-hover="tooltip" onclick="removeUser()" title="Delete Selected" class="btn btn-default">
<i class="fa fa-eraser"></i>
</button>
<button type="button" data-hover="tooltip" title="Add New User" class="btn btn-default">
<div class="panel-header" data-toggle="modal" data-target="#myModal">
<i class="fa fa-user-plus fa-1x"></i>
</div>
</button>
// #myModal codes here
<script type="text/javascript">
$(document).ready(function(){
$('.edit-row').live('click',function(){
var me = $(this);
var editModal = $('#myModalEdit');
editModal.find('#userID').val(me.attr('data-userID'));
editModal.find('#userName').val(me.attr('data-userName'));
editModal.find('#userFullName').val(me.attr('data-userFullName'));
editModal.find('#userPass').val(me.attr('data-userPass'));
editModal.find('#userEmail').val(me.attr('data-userEmail'));
$('#myModalEdit').modal('show');
});
});
</script>
//#myModalEdit codes here
<table id="userListTable" class="table table-hover table-striped table-bordered" >
<thead>
<tr>
<th><center><strong>#</strong></center></th>
<th><h4><strong>USER ID</strong></h4></th>
<th><h4><strong>FULL NAME</strong></h4></th>
<th><h4><strong>USERNAME</strong></h4></th>
<th><h4><strong>EMAIL</strong></h4></th>
</tr>
</thead>
<tbody>
<?php
if(!empty($data_user)):
foreach($data_user as $row)
{
echo '<tr>
<td class="text-center">
<input type="checkbox" name="selectAction" value="'.$row->userID.'" unchecked>
</td>';
echo '<td>'.$row->userID.'</td>';
?>
<td><a class="edit-row" href="javascript:"
data-userID="<?php echo $row->userID; ?>"
data-userFullName="<?php echo $row->userFullName; ?>"
data-userName="<?php echo $row->userName; ?>"
data-userEmail="<?php echo $row->userEmail; ?>"
>
<?php echo $row->userFullName; ?>
</a>
</td>
<?php
echo '<td>'.$row->userName.'</td>';
echo '<td>'.$row->userEmail.'</td>';
echo '</tr>';
}
endif;
?>
</tbody>
</thead>
</table>
// other codes
application/controllers/Admin.php
public function userRemove() {
$ids = $this->input->post('ids');
if (!empty($ids)) {
$this->db->where('userID IN (' . $this->input->post('ids') . ')')
->
delete('user_tbl', $data);
}
redirect('userlist', 'refresh');
}
Edit and delete functions seems not working..
I am trying to update database records using ajax from the ajax response, getting success message but the actual database records are not updated at all. But it wonder how the ajax response should throw the success message while the query is not updating the database.
VIEW:
// AJAX code to update the database
// update marks when form is submitted
$('#updateMarks').on('submit',function(event) {
event.preventDefault();
var practical_mark = $("#mark_written").val();
var written_mark = $("#mark_practical").val();
var comment = $("#comment").val();
var mark_id = $("#mark_id").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
alert("success");
},
error: function(){
alert("Error");
},
});
});
<?php foreach($marks as $row2): ?>
<form method="post" role="form" id="updateMarks">
<tr>
<td class="text-center"><?php echo $student['name']; ?></td>
<td>
<!-- create two col table for marks category -->
<table class="table table-bordered table-hover toggle-circle">
<thead>
<tr>
<th data-toggle="true" class="text-center"><?php echo get_phrase('written_exam'); ?></th>
<th data-toggle="true" class="text-center"><?php echo get_phrase('practical_exam'); echo get_phrase('_(out_of_100)'); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><input type="number" value="<?php echo $row2['written_mark_obtained'];?>" id="mark_written" name="mark_written" class="form-control" /></td>
<td class="text-center"><input type="number" value="<?php echo $row2['practical_mark_obtained'];?>" id="mark_practical" name="mark_practical" class="form-control"/></td>
</tr>
</tbody>
</table>
<!-- end create two col table for marks category -->
</td>
<td class="text-center"><textarea class="form_control" id="comment" name="comment" rows="4" > <?php echo $row2['comment'] ?> </textarea></td>
<td class="text-center">
<input type="hidden" id="mark_id" name="mark_id" value="<?php echo $row2['mark_id'];?>" />
<button type="submit" class="btn btn-block btn-success btn-md"><i class="icon pe-pen" aria-hidden="true"></i><?php echo get_phrase('update'); ?></button>
</td>
</tr>
</form>
<?php endforeach; ?>
Controller:
function exam_marks_update(){
$data['written_mark_obtained'] = $this->input->post('written_mark');
$data['practical_mark_obtained'] = $this->input->post('practical_mark');
$data['comment'] = $this->input->post('comment');
$this->crud_model->update_student_marks($data, $this->input->post('mark_id'));
}
MODEL
function update_student_marks($data, $mark_id){
$this->db->where('mark_id', $mark_id);
$this->db->update('mark', $data);
}
Jquery ajax success callback function is always called if the request to server succeeds. You need to return response data from server to verify when database operation was successful or not. I have edited your code , this might work for you.
MODEL
function update_student_marks($data, $mark_id){
.....
return $this->db->update('mark', $data);
}
Controller::
function exam_marks_update(){
.....
if($this->crud_model->update_student_marks($data, $this->input->post('mark_id'))){
echo json_encode(array('success' => true));
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
}
View
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
dataType :'json',
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
if (response.success === true){
alert("success");
} else {
alert('failed');
}
},
error: function(){
alert("Error");
},
});
Your Controller retrieving inputs which doesn't exists... you need to pass your name, id as inputs and not the value which you echo... see as Controller:
function exam_marks_update(){
$data = array(
'written_mark_obtained' => $this->input->post('written_mark'),
'practical_mark_obtained' => $this->input->post('practical_mark'),
'comment' => $this->input->post('comment')
);
$this->db->where('mark_id', $this->input->post('mark_id'));
$this->db->update('mark', $data);
}
and change this:
var comment = $("#comment").val();
to
var comment = $("#comment").html();
As comment is textarea...