I have the following table where I have two buttons to delete and update.
When I delete it automatically removes the table row.
But when I edit the line and change the state, the user still sees the line, where it gets confusing because they don't know the lines that have already been edited and the ones left to edit.
So when changing state the row should also disappear from the table.
Code:
<div id="spoiler2" class="esconde">
<table class="table table-responsive" id="employee_table2">
<h1 style="font-size: 30px"><strong>Pedidos de Manutenção</strong></h1>
<thead>
<tr>
<th>Data</th>
<th>Valência</th>
<th>Descrição</th>
<th>Colaborador</th>
<th>Estado</th>
<th>Ação</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
<?php do{ ?>
<tr id="<?php echo $produto2["Id"]; ?>">
<td><?php echo $produto2["DataRegisto"]; ?></td>
<td><?php echo $produto2["Destino"]; ?></td>
<td><?php echo $produto2["Descricao"]; ?></td>
<td><?php echo $produto2["nome"]; ?></td>
<td><?php echo $produto2["Estado"]; ?></td>
<td><button type="button" name="edit" data-id="<?php echo $produto2["Id"]; ?>" id="open_<?php echo $produto2["Id"]; ?>" data-target="#add_data_Modal2" class="btn btn-warning btn-sm edit_data2" ><span class="glyphicon glyphicon-pencil"></span></button></td>
<td><button class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-trash"></span></button></td>
</tr>
<?php } while($produto2 = $result2->fetch_assoc()); ?>
</tbody>
</table>
</div>
js:
$(document).on('click', '.edit_data2', function(){
var employee_id2 = $(this).data('id');
$.ajax({
url:"./editarmanutencao",
method:"POST",
cache: false,
data:{employee_id2:employee_id2},
dataType:"json",
success:function(data){
console.log(data);
$('#Id2').val(data.Id);
$('#Tratamento').val(data.Tratamento);
$('#Estado2').val(data.Estado);
$('#Prestador').val(data.Prestador);
$('#employee_id2').val(data.Id);
$('#insert2').val("Gravar");
$("#add_data_Modal2").modal("show");
}
});
});
function inserir_registo2()
{
var dadosajax = {
'Id' : $("#Id2").val(),
'DataTermino' : $("#DataTermino").val(),
'Tratamento' : $("#Tratamento").val(),
'Estado' : $("#Estado2").val(),
'Prestador' : $("#Prestador").val()
};
$.ajax({
url: './resolucaomanutencao',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$("#add_data_Modal2").modal("hide");
}
});
}
How can I remove the table row by changing ajax's success state?
If i understand correctly, you want to remove row from table after successful Edit operation.
If this is the case, you can use following code...
function inserir_registo2()
{
let rowToBeRemoved = $("#"+$("#Id2").val());
var dadosajax = {
'Id' : $("#Id2").val(),
'DataTermino' : $("#DataTermino").val(),
'Tratamento' : $("#Tratamento").val(),
'Estado' : $("#Estado2").val(),
'Prestador' : $("#Prestador").val()
};
$.ajax({
url: './resolucaomanutencao',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$("#add_data_Modal2").modal("hide");
if(<<Condition>>) // in case you want to validate something before removing row
{
rowToBeRemoved.remove();
}
}
});
}
Save a reference to the parent row before the ajax call (e.g. var row = $(this).closest('tr')) and then, on success, remove it by row.remove().
I have asynchronously loaded form. When I submit the form by clicking the submit button, it submits multiple times. I have gone through some of the SO answers but still the problem is there.
Form:
<form action="" method="POST" id="aproveForm" class="smart-form" novalidate="novalidate">
<fieldset>
<section class="col col-5" >
<select class="form-control" name="groupid" onchange="loadInvoice(this.value);">
<option value="1">Sales</option>
<option value="2">Merchandiser</option>
</select>
</section>
</fieldset>
</form>
JS
function loadInvoice(id){
nid= 'id='+id;
$.ajax({
type:'POST',
url:'loadform.php',
data:nid,
dataType:'html',
success:function(data) {
$('#payform').html(data);
}
});
}
in the <div id="payform">, I have loaded the form from loadform.php which is like below:
<form method="POST" id="mulpayment">
<table class="table table-bordered" style="width:80%;">
<tr>
<th><div align="center">Name of Customer</div></th>
<th><div align="center">New Payment</div></th>
<th><div align="center">Total Debit</div></th>
</tr>
<?php
alldebt=0;
foreach($linvoice as $row): ?>
<input type="hidden" id="gcustomer" name="gcustomer[]" value="<?php echo $row['customerid']; ?>">
<?php
echo "<tr>";
echo "<td><div align=left>".$row['name'].".</div></td>";
echo '<td><input type="text" id="gpay" name="gpay[]" min="0" required style="width:100%;"></td>';
echo '<td align="right"><i class="fa fa-inr"></i> '.$row['totaldebit'].'</td>';
echo "</tr>";
$alldebt += $row['totaldebit'];
endforeach;
?>
<tr>
<th colspan="3"><div align="right">Total</div></th>
<th><div align="right"><i class="fa fa-inr"></i> <?php echo number_format($alldebt,2); ?></div></th>
</tr>
<tr>
<td colspan="6">
<div align="right">
<input type="submit" id="savePayment" value="Save Payment" class="btn btn-success">
</div>
</td>
</tr>
</table>
</form>
When I submit the form, it submits multiple times,i.e., paymentupdate.php runs multiple times. I want to run paymentupdate.php one time only. How do I solve this problem? Please help.
$(document).on("submit", "#mulpayment", function(e){
e.preventDefault();
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
}else{
alert(data.msg);
}
}
});
return false;
});
Try adding disable to your button after submitting your form. like for example
$(document).on("click", "#mulpayment", function(e){
e.preventDefault();
$(':input[type="submit"]').prop('disabled', true);
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
$(':input[type="submit"]').prop('disabled', false);
}else{
alert(data.msg);
}
}
});
});
in this way, it can prevent from clicking multiple times. you can enable back the button once the ajax request succeeds.
Try change button type="submit" for type="button":
$(document).on("click", "#mulpayment", function(e){
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
}else{
alert(data.msg);
}
}
});
});
And remove action and method attributes from the form tags, you dont need it if you use ajax:
<form id="aproveForm" class="smart-form" novalidate="novalidate">
<form id="mulpayment">
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...
Hi all i'm trying to doing C.R.U.D on codeigniter with Ajax but i don't have any experience in Ajax.
So first i have done with add function. Its work but i want after add or edit to refresh table.
This is my modal which is for update :
<!-- Update Interview-->
<div class="modal fade" id="interview" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true">
<div class="modal-dialog">
<div id="form-content">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">Edit Your Detail</h4>
</div>
<div class="modal-body">
<?php
echo form_open('vacancy/interview/'. $row['id'], array("class" => "no-error-margin interview", "name" => "interview" , "id" => "edit-stage"));
?>
<div class="form-group">
<label class="control-label">Type:</label>
<select id="classinput" tabindex="1" name="priority" class="form-control required">
<option value="A">First Interview</option>
<option value="B">Second Interview</option>
<option value="B">Final Interview</option>
</select>
</div>
<div class="date-form">
<div class="control-group">
<label class="control-label" style="margin: 0 30%;padding: 7px;">When The Interview Will Be?</label>
<div class="container">
<div class="row">
<div class='col-sm-6 col-md-offset-3'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer ">
<button id="uin" type="submit" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
<!-- /.modal-content -->
</form>
</div>
<!-- /.modal-dialog -->
</div>
</div>
i try with following Ajax code for update:
$("#uin").click(function(){
$.ajax({
type: "POST",
url: "vacancy/interview/<?= $row['id'] ?>", //process
data: $('form.interview').serialize(),
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide'); //hide popup
},
error: function(){
alert("failure");
}
});
});
But getting Codeigniter Error The action you have requested is not allowed.
Controller function:
public function interview($i)
{
$type=$this->input->post();
$this->vacancies->update_interview($type, array("id" => $id));
}
and Model
public function update_interview($i)
{
$this->db->insert("interviews", $i);
}
Can you tell me where i'm wrong?
For the error
The action you have requested is not allowed
you have CSRF protection enabled
$config['csrf_protection'] = TRUE;.
Try disabling this in your config.php and see if it works. In general you should use CSRF for security purposes anyway. To implement this correctly you should add the csrf token to your ajax post data so that Codeigniter can see and validate each form and each ajax request you do.
A simple example of adding CSRF to your AJAX is the following:
var cct = $.cookie('<?php echo $this->config->item("csrf_cookie_name"); ?>');
var request = $.ajax({
url: "/action/doaction",
type: "POST",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>': cct }
});
Crud operation with Import, Export Using Ajax.
Create a file view.php
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<html>
<head>
<div id="myDropdown" class="dropdown-content">
Registration Form
User Listing
</div>
<div align="center"><h3>Registration Form</h3></div>
</head>
<body>
<form id="signup_form" method="post" action="" enctype="multipart/form-data" >
<table border="1" align="center" width="450">
<tr>
<td>First Name</td>
<td>
<input type="text" name="first_name" id="first_name" value="<?php echo !empty($editRecord[0]->first_name) ? $editRecord[0]->first_name :'' ?>">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input type="text" name="last_name" id="last_name" value="<?php echo !empty($editRecord[0]->last_name) ? $editRecord[0]->last_name :'' ?>">
</td>
</tr>
<tr>
<?php echo validation_errors(); ?>
<td>Email</td>
<td>
<input type="email" name="email" id="email" onblur="check_email(this.value);" value="<?php echo !empty($editRecord[0]->email) ? $editRecord[0]->email :'' ?>">
<label id="message"></label>
</td>
</tr>
<tr>
<td>Mobile Number</td>
<td>
<input type="text" name="mobile_no" id="mobile_no" onkeypress="return isNumber(event)" data-range='[1,9999999999]' maxlength="15" value="<?php echo !empty($editRecord[0]->mobile_no) ? $editRecord[0]->mobile_no :'' ?>">
</td>
</tr>
<tr>
<tr>
<td>Gender</td>
<td>
<select name="gender" id="gender">
<option value="">Select Gender</option>
<option value="0" <?php if(!empty($editRecord[0]->gender) && $editRecord[0]->gender == 0) echo "selected" ;?>>male</option>
<option value="1" <?php if(!empty($editRecord[0]->gender) && $editRecord[0]->gender == 1) echo "selected"; ?>>Female</option>
</select>
</td>
</tr>
<td>Address</td>
<td>
<textarea name="address" id="address"><?php echo !empty($editRecord[0]->address) ? $editRecord[0]->address :'' ?></textarea>
</td>
</tr>
<?php if(empty($editRecord))
{
?>
<tr>
<td>Password</td>
<td>
<input type="password" name="password" id="password" value="">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input type="password" name="cpassword" id="cpassword" value="">
</td>
</tr>
<?php
}
?>
<tr>
<td>Image</td>
<div class="fileinput fileinput-new" data-provides="fileinput">
<td class="fileinput-preview thumbnail" data-trigger="fileinput" style = "width: 20px; height: 20px;"><img src="<?php echo base_url() ?>/uploads/<?php echo !empty($editRecord[0]->image) ? set_value("title", $editRecord[0]->image) : set_value("title","images.jpg"); ?>">
<!-- <input type="file" name="file" id="file" value="<?php echo !empty($editRecordRecord[0]->file) ? $editRecordRecord[0]->file :'' ?>"> -->
<input type="file" name="user_files" id="user_files" value="<?php echo !empty($editRecord[0]->image) ? set_value("title", $editRecord[0]->image) : set_value("title","images.jpg"); ?>" >
</td>
</div>
<input type="hidden" name="picture_name" value="<?php echo isset($editRecord[0]->image) ? set_value("title", $editRecord[0]->image) : set_value("title",""); ?>" >
</tr>
<tr collspan="2">
<td align="center">
<input type="submit" name="submit" value="submit">
</td>
</tr>
</table>
<input type="hidden" name="id" id="id" value="<?= !empty($editRecord[0]->id)?$editRecord[0]->id:'';?>" >
</form>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.5.0/js/fileinput.js" type="text/javascript"></script>
<script type="text/javascript">
$("#signup_form").validate({
onkeyup: false,
rules:{
first_name: {
required: true
},
last_name: {
required: true
},
email:{
required: true,
email: true,
},
mobile_no:{
required:true,
minlength:10,
maxlength:15
},
password:{
required:true,
minlength:6,
normalizer: function(value){
return $.trim(value);
},
password_check: true
},
cpassword:{
required:true,
normalizer: function(value){
return $.trim(value);
},
equalTo: "#password",
},
},
messages:{
first_name:{
required: "First Name cannot be blank.",
},
last_name:{
required: "Last Name cannot be blank.",
},
email:{
required: "Email cannot be blank.",
},
mobile_no:{
required: "Mobile number cannot be blank",
minlength: "Please enter minimum 10 digit number.",
maxlength: "Contact Number not allow more then 15 digit."
},
password:{
required: "Password cannot be blank.",
minlength: "Password should be at least 6 character long."
},
cpassword:{
required: "Confirm Password cannot be blank.",
equalTo: "Password and Confirm Password must be same."
},
},
});
jQuery.validator.addMethod('password_check', function(value,element)
{
var pattern = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{6,}$/);
//
if(pattern.test(value))
{
return true;
}else{
return false;
}
},"Password should be 6 character long, one special character, one uppercase, one lowercase letter and one digit.");
function isNumber(evt)
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 32 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
$('#signup_form').submit(function(e) {
var id = $('#id').val();
e.preventDefault();
if(id == '')
{
url = "<?php echo base_url('user_management/insert_record/');?>" + $("#id").val();
$.ajax({
url:url,
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
if (data == 1) {
//setTimeout(function(){document.location.href = "index"},500);
toastr.success('Recored Added Successfully.', 'Success Alert', {timeOut: 5000});
}
$('#signup_form').trigger("reset");
},
error: function() { alert("Error posting feed."); }
});
}
else
{
url = "<?php echo base_url('user_management/update_record/');?>" + $("#id").val();
$.ajax({
url:url,
type:"post",
data:new FormData(this),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
if (data == 1) {
toastr.success('Recored Updated Successfully.', 'Success Alert', {timeOut: 5000});
setTimeout(function(){document.location.href = "index"},5000);
}
//$('#signup_form').trigger("reset");
},
error: function() { alert("Error posting feed."); }
});
}
});
function check_email(email)
{
var id = $('#id').val();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>'+"user_management/check_email",
dataType: 'json',
async: false,
data: {'email':email,'id':id},
success: function(data){
if(data == '1')
{$('#email').focus();
$('#submit').attr('disabled','disabled');
$.confirm({
title: 'Alert',
content: " <strong> This email already existing. Please select other email. "+"<strong></strong>",
buttons: {'ok' : {'class' : 'btn_center alert_ok',
action: function(){
$('#email').focus();
$('#email').val('');
$('#submit').removeAttr('disabled');
}}}});
}
}
});
return false;
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#profile').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#user_files").change(function(){
readURL(this);
});
</script>
I user jQuery validation for validate the fields.
Create a file to show details list.php
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.5.0/css/fileinput.css" rel="stylesheet" type="text/css" />
<html>
<body>
<table border="2" align="center">
<tr>
<td width="30">#</td>
<td>Name</td>
<td>Email</td>
<td>Mobile No.</td>
<td>Gender</td>
<td>Address</td>
<td>Image</td>
<td>Action</td>
</tr>
<?php
foreach($user_details as $user)
{
?>
<tr>
<td><?php echo $user->id;?></td>
<td><?php echo ucwords($user->name);?></td>
<td><?php echo $user->email;?></td>
<td><?php echo $user->mobile_no;?></td>
<td><?php
if($user->gender == 0)
{
echo "Male";
}elseif ($user->gender == 1) {
echo "Female";
}
?>
</td>
<td><?php echo $user->address;?></td>
<td><img style="width: 50px;height: 40px;" src="<?php echo base_url('uploads/'. $user->image);?>" /></td>
<td>
Edit
<span class='delete' id='del_<?php echo $user->id; ?>'>Delete</span>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="2">Add new</td>
<td colspan="1">
<div class="col-md-3">
<form action="<?php echo site_url("User_management/ExportCSV");?>" method="post" enctype="multipart/form-data" id="exportFrm"> <input type="submit" class="btn btn-success howler" name="exportSubmit" value="Export">
</form>
</div>
</td>
<td colspan="2">
<div class="col-md-2 pull-right">
Import Users
</div>
</td>
<td colspan="3">
<form action="<?php echo site_url("User_management/upload_file");?>" method="post" enctype="multipart/form-data" id="importFrm">
<input type="file" name="file" />
<input type="submit" class="btn btn-primary" name="importSubmit" value="Import">
</form>
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
// AJAX Request
$.ajax({
url: "<?php echo base_url('user_management/delete/');?>",
type: 'POST',
data: { id:deleteid },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
});
});
</script>
<style type="text/css">
.panel-heading a{float: right;}
#importFrm{margin-bottom: 20px;display: none;}
#importFrm input[type=file] {display: inline;}
</style>
now create model Common_model.php
<?php
Class Common_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
function encrypt_script($string)
{
$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
$qEncoded = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $string, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
return( $qEncoded );
}
function decrypt_script($string)
{
$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
$qDecoded = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
return( $qDecoded );
}
function insert($table,$data)
{
$this->db->insert($table,$data);
return $this->db->insert_id();
}
function get_users()
{
$this->db->select('id, CONCAT(`first_name`," ", `last_name`) AS `name` ,email,mobile_no,gender,address,image');
$result = $this->db->get('user_master');
return $result->result();
}
public function get_user_detail($id){
$this->db->select('*');
$this->db->where('id',$id);
$result = $this->db->get('user_master');
return $result->result();
}
public function update($table,$data,$where)
{
if(!empty($where))
$this->db->where($where);
$this->db->update($table, $data);
}
public function delete($table, $where)
{
$this->db->where($where);
$this->db->delete($table);
}
public function select_where($table,$where)
{
$rec=$this->db->get_where($table,$where);
return $rec->result();
}
}
?>
Now create controller user_management_control.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
Class User_management extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Common_model');
}
public function index()
{
$data['user_details'] = $this->Common_model->get_users();
$this->load->view('user/list',$data);
}
public function add()
{
$this->load->view('user/add');
}
public function insert_record()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('user_files'))
{
$photo.= $data['image'] = $this->input->post('picture_name');
}
else
{
$data = array('upload_data' => $this->upload->data());
global $photo ;
$photo .= $data['upload_data']['file_name'];
}
$this->load->library('form_validation');
if($this->input->server('REQUEST_METHOD') == 'POST')
{
$this->form_validation->set_rules('first_name','First Name','trim|required');
$this->form_validation->set_rules('last_name','Last Name','trim|required');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('mobile_no','Mobile Number','trim|required');
$this->form_validation->set_rules('password','Password','trim|required|matches[cpassword]');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('user/add');
}
else
{
$post_array = $this->input->post();
$data = array(
'first_name' => $post_array['first_name'],
'last_name' => $post_array['last_name'],
'email' => strtolower(trim($post_array['email'])),
'mobile_no' => $post_array['mobile_no'],
'gender' => $post_array['gender'],
'address' => $post_array['address'],
'password' => $this->Common_model->encrypt_script($post_array['password']),
'status' => 0,
'image'=>$photo,
'inserted_date' => date('Y-m-d H:i:s')
);
$inser_data = $this->Common_model->insert('user_master',$data);
if(!empty($inser_data))
{
echo '1';
}
else{
echo '0';
}
}
}
}
public function check_email()
{
$id = $this->input->post('id');
$email=$this->input->post('email');
$exist_email= $this->Common_model->select_where('user_master',array('email'=>$email));
if(!empty($exist_email))
{
if($exist_email[0]->id == $id)
{
echo '0';
}
else
{
echo '1';
}
}
else
{
echo '0';
}
}
public function edit_record()
{
$id = $this->uri->segment(3);
$result = $this->Common_model->get_user_detail($id);
if(empty($result))
{
redirect('user_management/');
}
$data['editRecord'] = $result;
$this->load->view('user/add',$data);
}
public function update_record()
{
if(!empty($_FILES['user_files']['name']))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->do_upload('user_files');
$data['image'] = $this->upload->data('file_name');
}
else
{
$data['image'] = $this->input->post('picture_name');
}
$this->load->library('form_validation');
if($this->input->server('REQUEST_METHOD') == 'POST')
{
$this->form_validation->set_rules('first_name','First Name','trim|required');
$this->form_validation->set_rules('last_name','Last Name','trim|required');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('mobile','Mobile Number','trim|required');
$post_array = $this->input->post();
$cdata['id'] = $post_array['id'];
if(!empty($cdata['id'])){
$data = array(
'first_name' => $post_array['first_name'],
'last_name' => $post_array['last_name'],
'email' => strtolower(trim($post_array['email'])),
'mobile_no' => $post_array['mobile_no'],
'gender' => $post_array['gender'],
'address' => $post_array['address'],
'image' => $data['image'],
'status' => 0,
'modified_date' => date('Y-m-d H:i:s')
);
//echo'<pre>';print_r($data);echo'<pre>';
$this->Common_model->update('user_master',$data,array('id' =>$cdata['id']));
echo '1';
}
else{
echo '0';
}
}
}
public function delete()
{
$id = $_POST["id"];
if(!empty($id))
{
$this->Common_model->delete('user_master',array('id'=>$id));
echo '1';
}else{
echo '0';
}
}
public function upload_file()
{
$csvMimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes))
{
if(is_uploaded_file($_FILES['file']['tmp_name'])){
//open uploaded csv file with read only mode
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
// skip first line
// if your csv file have no heading, just comment the next line
fgetcsv($csvFile);
//parse data from csv file line by line
while(($line = fgetcsv($csvFile)) !== FALSE){
//check whether member already exists in database with same email
$result = $this->db->get_where("user_master", array("email"=>$line[2]))->result();
if(count($result) > 0){
//update user_master data
$this->db->update("user_master", array("first_name"=>$line[0], "last_name"=>$line[1], "mobile_no"=>$line[3], "gender"=>$line[4],"address"=>$line[5]), array("email"=>$line[2]));
}else{
//insert user_master data into database
$this->db->insert("user_master", array("first_name"=>$line[0], "last_name"=>$line[1], "email"=>$line[2], "mobile_no"=>$line[3], "gender"=>$line[4],"address"=>$line[5]));
}
}
//close opened csv file
fclose($csvFile);
$qstring["status"] = 'Success';
}else{
$qstring["status"] = 'Error';
}
}else{
$qstring["status"] = 'Invalid file';
}
redirect('user_management');
}
public function ExportCSV()
{
$this->load->dbutil();
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "user.csv";
$query = "SELECT * FROM user_master WHERE 1";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
}
?>