Using Ajax on CRUD in Codeigniter - javascript

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);
}
}
?>

Related

Filter date from data base with ajax and jquery with the help of form?

I have four file in php first one is feedback that contain data table where I try to display my data feedback.php are below
<?php
error_reporting(E_ALL);
ini_set('display_error',1);
include_once('header.php');
//include_once('sidemenu.php');
require_once('Class_Library/class_Feedback.php');
?>
<?php
$obj = new Feedback();
//$clientid = $_SESSION['clientId'];
$feedbackdata = $obj->GetAllFeedback();
if($feedbackdata['success']==1)
{
$data=$feedbackdata['data'];
//print_r($data);
}
else {
$data=[];
}
//print_r($fedbackdata);
//die;
?>
<style>
.dataTables_filter {
float: right;
}
.pagination{
float: right;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="js/home_page.js"></script>
<script>
$(document).ready(function () {
var startdate = document.getElementById("feedbackstartdate").value;
var enddate = document.getElementById("feedbackenddate").value;
var site = document.getElementById("site").value;
// alert("end "+enddate);
// alert("start "+startdate);
$feedbackdata=showfeedbacklist(startdate, enddate,site);
});
</script>
<script>
function feedbackindex()
{
//alert("hello, your code is here");
var startdate= document.getElementById("fromDate").value;
var enddate= document.getElementById("toDate").value;
var site= document.getElementById("site").value;
//alert('start '+startdate);
//alert('enddate '+enddate);
if (startdate == "")
{
window.alert("Please select From date.");
document.getElementById("fromDate").focus();
return false;
}
if (enddate == "")
{
window.alert("Please select To date.");
document.getElementById("toDate").focus();
return false;
}
if (startdate > enddate )
{
window.alert("From date can't be greater then To date.");
document.getElementById("toDate").focus();
return false;
}
$feedbackdata = showfeedbacklist(startdate, enddate,site);
/**************************************************************************/
}
</script>
<!--page content -->
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="margin-top: 25px;">
<div class="panel-heading">
<h4>Feedback</h4>
</div>
<form id="formdata" method="post">
<div class="col-md-4">
<div class="form-group">
<label for="pwd">From: </label>
<input type="date" id="fromDate" name="FSDate" size="20" class="form-control input" placeholder="mm/dd/yyyy"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="pwd">To: </label>
<input type="date" id="toDate" class="form-control" name="FSDate" size="20" placeholder="mm/dd/yyyy"/>
</div>
</div>
<div class="col-md-4" style="margin-top:20px;">
<div class="form-group">
<input type="hidden" name="feedbackstartdate" id="feedbackstartdate" value="<?php echo date('Y-m-d', strtotime("-7 days")); ?>">
<input type="hidden" id="feedbackenddate" name="feedbackenddate" value="<?php echo date('Y-m-d', strtotime("-1 days")); ?>">
<input type="" id="site" name="site" value="<?php echo SITE; ?>"
<center><button type="button" class="btn btn-info" onclick="return feedbackindex();">Submit</button></center>
</div>
</div>
</form>
<div class="panel-body">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead>
<tr>
<th>Cutomer Name</th>
<th>Location</th>
<th>Visit Type</th>
<th>Visit By</th>
<th>Visit Dtae</th>
<th>Feedback</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($data); $i++) {
?>
<tr>
<td><?php echo $data[$i]['CustomerName'];?></td>
<td><?php echo $data[$i]['clientCity']; ?></td>
<td><?php echo $data[$i]['TaskType']; ?></td>
<td><?php echo $data[$i]['visitByName']; ?></td>
<td><?php echo $data[$i]['visitDate'];?></td>
<td><?php
$datafeedback = $data[$i]['feedbackValue'];
if($datafeedback==null)
{
echo 'pending';
}
else{
if($datafeedback==5)
{
echo '<img src="images/feedback/greenSmile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
elseif ($datafeedback==4) {
echo '<img src="images/feedback/smile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
elseif ($datafeedback==3) {
echo '<img src="images/feedback/redsmile.png" alt="send feedback by data"style="width:50px;height:50px;" />';
}
}
?></td>
<td>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!--/page content -->
<?php include 'footer.php'; ?>
My code is proper work when we try to display to data but when we try to filter I don't know how to work that and my link file of js are
function showfeedbacklist(startdate, enddate, site)
{
var postData =
{
"startdate":startdate ,
"enddate": enddate,
"site" :site
};
var dataString = JSON.stringify(postData);
// alert(dataString);
$.ajax({
type: "post",
// dataType: "json",
//contentType: "application/json; charset=utf-8",
url:site+"Link_Library/link_getfeedbacklist.php",
data: {"mydata": dataString},
success: function (response) {
var respdata = response;
// alert(respdata);
console.log(respdata);
},
error: function (e) {
alert(e);
console.log(e.message);
}
});
}
and my ajax page where i am send to data are
<?php
require_once('../Class_Library/class_Feedback.php');
$obj = new Feedback();
if (!empty($_POST["mydata"])) {
$jsonArr = $_POST["mydata"];
// echo $jsonArr;
$data = json_decode($jsonArr, true);
//print_r($data);
//die;
if (!empty($data)) {
$fromdt1 = $data['startdate'];
$fromdt = date("Y-m-d H:i:s", strtotime($fromdt1));
// echo "statrt date-".$fromdt;
$enddte1 = $data['enddate'];
$enddte2 = date("Y-m-d", strtotime($enddte1));
$date123 = date_create($enddte2 ." 23:59:59", timezone_open("Asia/Kolkata"));
$enddate = date_format($date123, "Y-m-d H:i:s");
// echo "endd date-".$enddt;
$result = $obj->graphGetFeedbacklist($enddate, $fromdt);
// echo "<pre>";
// print_r($res);
}
}
?>
And my sql class file are last one that is
<?php
if (!class_exists('Connection_Communication')) {
include_once('class_connect_db_Communication.php');
}
class Feedback {
public $DB;
public function __construct() {
$db = new Connection_Communication();
$this->DB = $db->getConnection_Communication();
}
function GetAllFeedback() {
try {
$query = "select site.*,list.Service_Type,list.Id,(select Task_Type from tbl_task_type where Auto_Id = list.Service_Type) as TaskType,DATE_FORMAT(start_date,'%d-%b-%Y') as visitDate,CONCAT(usr.First_Name,' ',usr.Last_Name) as visitByName,(select SUM(parameter_value)/(select count(parameterId) from tbl_visit_feedback_parameter where parameterId < (select MAX(parameterId) from tbl_visit_feedback_parameter)) from tbl_visit_feedback_data where parameter_id < (select MAX(parameterId) from tbl_visit_feedback_parameter) and task_id = site.task_id) as feedbackValue from tbl_site_visit_detail as site JOIN tbl_master_user as usr ON site.employee_id = usr.ID JOIN tbl_tasks_list as list ON site.task_id = list.Task_Id where visit_status = '1'";
$stmt = $this->DB->prepare($query);
// $stmt->bindParam(':sd', $startdate, PDO::PARAM_STR);
// $stmt->bindParam(':ed', $enddate, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($row) {
require_once 'class_master.php';
$masObj = new Master();
$farray = array();
for ($i = 0; $i < count($row); $i++) {
$refid = $row[$i]['Id'];
$Service_Type = $row[$i]['Service_Type'];
$result = $masObj->getTaskDetail($refid, $Service_Type);
if ($result['success'] == 1) {
$data = $result['data'];
$temp = $data + $row[$i];
array_push($farray, $temp);
}
}
if (!empty($farray)) {
$response['success'] = 1;
$response['data'] = $farray;
} else {
$response['success'] = 0;
$response['message'] = 'No data found.';
}
} else {
$response['success'] = 0;
$response['data'] = 'error while fetching data ';
}
} catch (Exception $ex) {
$response['success'] = 0;
$response['data'] = $ex->getMessage();
}
return $response;
}
}
?>
I am new in codding area so i don't know how to handle that type problem and I sow so many references but I have no idea what happen there.

Update Database Record with Ajax in Codeigniter

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...

noty jQuery - notification apearence

I want to show notification on delete all button. I use noty jquery while I click on delete all button only button of notification show not full and page redirected I am using codeigniter what I do the code below like as
// view of my file
<?php $page_url = $this->uri->segment(2);?>
<div id="contents" style="width:1024px;">
<div class="buttons">
<div><button class="button-choose-2 pure-button" id="delete">Delete</button></div>
<div>
<input type="button" class="button-choose-2 pure-button" name="CheckAll" value="Check All" onClick="checkAll(document.myform.list)"></div>
<div>
<input type="button" class="button-choose-2 pure-button" name="UnCheckAll" value="Uncheck All" onClick="uncheckAll(document.myform.list)"></div>
<div><button class="button-choose-2 pure-button">Add</button></div>
</div>
<br style="clear:both;">
<?php $this->load->view("includes/left_menu") ?>
<form name="myform" id="myform">
<div class="right-contents">
<table width="98%" cellpadding="5">
<tr class="right-top">
<td width="8%"> </td>
<td width="21%">Name</td>
<td width="18%">Image</td>
<td width="38%">Designation</td>
<td colspan="3" align="center">Actions</td>
</tr>
<?php if(is_array($items)): ?>
<?php foreach($items as $row){?>
<tr>
<td width="8%"><input type="checkbox" id="list" name="del[]" value="<?php echo $row->team_id;?>" class="del"></td>
<td width="21%"><?php echo $row->name?></td>
<td width="18%"><img src="assets/icons/<?php echo $row->photo?>" width="100" height="70"></td>
<td width="38%"><?php echo $row->designation?></td>
<td width="5%"><img src="assets/img/edit.png"></td>
<td width="5%"><img src="assets/img/27935.png"></td>
<td width="5%"><a href="parexons_con/delete/<?php echo
$row->team_id;?>/<?php echo $page_url ?>/<?php echo 'team'; ?>/<?php echo 'team_id'; ?>"><img src="assets/img/Delete-icon.png"></a></td>
</tr>
<?php } endif; ?>
</table>
</div>
</form>
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#delete").on('click', function(e) {
var r = confirm("are you sure you want to delete this");
if (r==true) {
e.preventDefault();
var ids = $('.del:checked').map(function () {
return this.value;
}).get();
console.log(ids);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>parexons_con/delete_all",
data: 'id=' + ids,
type: "POST",
success: function (result) {
noty({text: 'thank you for providing information', type: 'success',settimeout:5000});
setTimeout(window.location.reload(), 1200000);
}
});
}
});
});
</script>
and controller are
function delete_all($del_id = NULL, $view = NULL, $table = NULL, $field_name = NULL)
{
$error = 'error';
$msg = 'deleted';
$ids = $this->input->post('id');
$explode = explode(",", $ids);
foreach ($explode as $id) {
$query = $this->parexons_model->delete_row('team', array('team_id' => $id));
}
if ($query) {
http_response_code(redirect("my_controller/team"), 5000);
} else {
redirect("my_controller/team");
}
}
Wrong syntax of jquery ajax data it would be
data: {id: ids},
Second do not redirect of controller function you need to pass some value to ajax success like
function delete_all($del_id = NULL, $view = NULL, $table = NULL, $field_name = NULL) {
$error = 'error';
$msg = 'deleted';
$ids = $this->input->post('id');
$explode = explode(",", $ids);
foreach ($explode as $id) {
$query = $this->parexons_model->delete_row('team', array('team_id' => $id));
}
if ($query) {
echo "success";
} else {
echo "false";
}
}

update multiple checkbox with javascript and ajax

I am working with multiple checkboxes with javascript and ajax. When the checkbox is clicked the javascript send with ajax the values to trata.php (these values: checked if is true or false and the id of that checkbox)...but the id always show me undefined....can you guide me, please.
Here is the JS:
$("div.feature").click(function() {
var checked = $(this).is(':checked');
var Id = $(this).attr('id');
var data = "Cara=" + checked + "&Id=" + Id;
$.ajax({
type: "POST",
url: "trata.php?ts=" + new Date().getTime(),
data: data,
cache: false,
beforeSend: function() {
$("#tr").show();
$("#t").empty();
},
success: function(response) {
$("#tr").hide();
$("#t").append(response);
}
})
return false;
});
$("div.feature1").click(function() {
var checked = $(this).is(':checked');
var Id = $(this).attr('id');
var data = "Pieza=" + checked + "&Id=" + Id;
$.ajax({
type: "POST",
url: "trata.php?ts=" + new Date().getTime(),
data: data,
cache: false,
beforeSend: function() {
$("#tr").show();
$("#t").empty();
},
success: function(response) {
$("#tr").hide();
$("#t").append(response);
}
})
return false;
});
In page this is the code:
<table>
<tr>
<td>
<div class="feature" align="center">
<input type="text" value="<?php echo $row['Id'] ?>" name="Id" id="Id" /> <!-- in this Id the value is 1 -->
<input type="checkbox" data-no-uniform="true" class="iphone-toggle" <?php if ($row[ 'Cara']=='1' ) {echo 'name="Cara" value="on" checked="checked"';} else { echo 'name="Cara" value="off"'; } ?>>
</div>
<div id="tr" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" />
</div>
<div id="t"></div>
</td>
<td>
<div class="feature1" align="center">
<input type="text" value="<?php echo $row['Id']; ?>" name="Id" id="Id" /> <!-- in this Id the value is 2 -->
<input type="checkbox" data-no-uniform="true" class="iphone-toggle" <?php if ($row[ 'Pieza']=='1' ) {echo 'name="Pieza" value="on" checked="checked"';} else { echo 'name="Pieza" value="off"'; } ?>>
</div>
<div id="tr" style="display:none;" align="center"><img src="img/ajax-loaders/ajax-loader-1.gif" />
</div>
<div id="t"></div>
</td>
</tr>
</table>
In trata.php //MySQL + PDO
<?php
include('conn.php');
if(isset($_POST['Cara'])) {
try{
$Id = $_POST['Id'];
if ($_POST['Cara'] == false) {
global $Cara;
$Cara = 0;
} else if ($_POST['Cara'] == true) {
global $Cara;
$Cara = 1;
};
$sql = "UPDATE Trata SET
Cara = :Cara
WHERE Id= :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':Cara', $Cara, PDO::PARAM_STR);
$stmt->bindParam(':Id', $Id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-primary fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
ok.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
} if(isset($_POST['Pieza'])) {
try{
$Id = $_POST['Id'];
if ($_POST['Pieza'] == false) {
global $Pieza;
$Pieza = 0;
} else if ($_POST['Pieza'] == true) {
global $Pieza;
$Pieza = 1;
};
$sql = "UPDATE Trata SET
Pieza = :Pieza
WHERE Id= :Id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':Pieza', $Pieza, PDO::PARAM_STR);
$stmt->bindParam(':Id', $Id, PDO::PARAM_INT);
$stmt->execute();
echo "<div class='alert alert-block alert-primary fade in'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
ok.
</div>";
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
$dbh = null;
?>
Another thing is the loading ajax is show me only in the first td and I have 8 td files..
div.feature and div.feature1 do not have ids. That is why $(this).attr('id') is returning undefined. Try this:
$('div.feature input:checkbox').click(function(){
var Id = $(this).attr('id');
});

How To Integrate Codeigniter Form Validation Library and file uploading in a form using jQuery AJAX ?

this is my controller file
below code is working only file uploading into path and no data is displaying in database when i gave inputs. Another doubt, It is not showing validation errors when i submit with empty inputs.
var $default_news_status = 1;
var $default_client_status = 1;
var $default_client_partner_flag = 0;
var $default_client_logo_display_flag = 1;
var $default_client_test_status = 0;
public function construct()
{
parent::__construct();
$this->load->helper(array('form', 'url', 'file'));
}
/*controlles vadmin/addnews*/
public function addnews()
{
//$status = "";
//$msg = "";
$userfile = 'userfile';
//echo '<br>entered into ajax if block.. ';
/******* extracting file extension ********/
$org_filename = $_FILES['userfile']['name'];
$path_parts = pathinfo($org_filename);
//$file_extension = $path_parts['extension'];
/***** end extracting file extension ******/
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[5]');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('url', 'URL', 'trim|required');
$this->form_validation->set_rules('userfile', 'Image', 'trim');
$this->form_validation->set_rules('postedon', 'Posted On', 'trim|required');
$this->form_validation->set_rules('source', 'Source','trim|required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('expiredate', 'Expire Date', 'trim|required');
if($this->form_validation->run() == FALSE)
{
echo json_encode(array('status'=>0, 'msg' => validation_errors()));
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 1000;
//$config['file_name'] = 'client_'.time().'.'.$file_extension;
//echo "<pre>";
//print_r($_FILES);
$this->load->library('upload', $config);
if (!$this->upload->do_upload($userfile))
{
echo '<br>entered into upload failed block.. ';
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
echo '<br>entered into upload success block.. ';
/*$data = $this->upload->data();
echo "<pre>";
print_r($data);*/
/**** assignment of post data ******/
$title = $this->input->post('title');
$description = $this->input->post('description');
$url = $this->input->post('url');
$userfile = $this->input->post('userfile');
$postedon = $this->input->post('postedon');
$source = $this->input->post('source');
$expiredate = $this->input->post('expiredate');
$status = $this->default_news_status ;
/**** end assignment of post data ******/
/**** load news model to insert reocrd into table *****/
$this->load->model('vadmin/Newsmodel','',true);
$this->Newsmodel->addRequestForm();
/**** load news model to insert reocrd into table *****/
//print jsone response for ajax request
echo json_encode(array('status'=>0, 'msg' => 'Successfully Submitted'));
}
}
here is my view form
and js file is given below
<form method="post" action="" name="newsform" id="newsform" enctype= "multipart/form-data" >
<input type="hidden" value="" id="id" name="id" required="true">
<table width="580" cellpadding="5" cellspacing="5">
<tr>
<td width="130" align="left"><span class="required">*</span>Title</td>
<td align="left"><input name="title" type="text" id="title" style="width:250px;" value="<?php echo $news_title; ?>"/></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Description</td>
<td align="left"><textarea name="description" rows="8" cols="40" id="description" style="width:250px;" ><?php echo $news_description; ?></textarea></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>URL</td>
<td align="left"><input name="url" type="text" id="url" style="width:250px;" value="<?php echo $news_url; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Image</td>
<td align="left"><input name="userfile" type="file" id="userfile" style="width:250px;" value="<?php echo $news_image; ?>" /></td>
<tr>
<td width="130" align="left"><span class="required">*</span>Posted On</td>
<td align="left"><input name="postedon" id="datepicker" style="width:250px;" value="<?php echo $news_posted_on; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Source</td>
<td align="left"><input name="source" type="text" id="source" style="width:250px;" value="<?php echo $news_source; ?>" /></td>
</tr>
<tr>
<td width="130" align="left"><span class="required">*</span>Expire Date</td>
<td align="left"><input name="expiredate" id="datepicker1" style="width:250px;" value="<?php echo $news_expire_date; ?>"/></td>
</tr>
<td colspan="2" align="left"><input type="submit" value="Submit" id="submit" onclick="return ajaxFileUpload();" />
<input type="reset" value ="reset" id="reset" /><span id="loading" >Please wait ..</span></td>
</tr>
</table>
<input type="hidden" name="nid" id="nid" value="<?php echo $news_id; ?>" />
</form>
here is my script
$.ajaxFileUpload
(
{
url:'<?php echo base_url();?>vadmin/ajax/addnews/',
secureuri:false,
fileElementId:'userfile',
dataType: 'json',
data: $("#newsform").serialize(),
beforeSend:function()
{
$("#loading").show();
},
complete:function()
{
$("#loading").hide();
},
success: function (resp)
{
if(resp.status == 0)
{
$('#message').css('color','red');
$('#message').html(resp.error).show(400);
}
if(resp.status == 1)
{
$('#message').css('color','green');
$('#message').html(resp.msg).show(400);
}
if(typeof(resp.error) != 'undefined')
{
if(resp.error != '')
{
alert(resp.error);
}else
{
alert(resp.msg);
}
}
},
/*error: function (resp, status, e)
{
alert('ajax error :: '+e);
} */
}
);
try like this
$data = $this->upload->data(); //remove comment
/*echo "<pre>";
print_r($data);*/
/**** assignment of post data ******/
$title = $this->input->post('title');
$description = $this->input->post('description');
$url = $this->input->post('url');
$userfile = $data['file_name']; // add this line
$postedon = $this->input->post('postedon');
$source = $this->input->post('source');
$expiredate = $this->input->post('expiredate');
$status = $this->default_news_status ;
for error try like this
if($this->form_validation->run() == FALSE)
{
echo json_encode(array('status'=>0, 'msg' => validation_errors()));
exit;
}

Categories

Resources