I have a strange problem here. I am processing data via AJAX from a table loaded inside while loop and when the data is successfully processed the table gets reloaded with new data via AJAX and JSON. The problem is that when the new table is loaded and I click the same submit button from any row again then this time instead of processing it via AJAX it works as a normal submit button and refreshes the page. Then when the page is refreshed the submit button works via AJAX again. Why is it not working with AJAX when the table was reloaded via AJAX after previous operation via AJAX when in both the tables the parameters used are exactly the same? My codes are below. Please tell my what's wrong here and what's the solution for this.
membership.php
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Memberships List</h3>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover table-striped" id="mbslist">
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$i = 1;
$mem = $pdo->prepare("SELECT * FROM memberships");
$mem-> execute();
while($m = $mem->fetch()){ extract($m);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
?>
<tr>
<td><?php echo $i; ?></td>
<td><span style="color: <?php echo $mem_color; ?>"><?php echo $mem_name; ?></span></td>
<td>₹<?php echo $mem_daily_capping; ?></td>
<td>₹<?php echo $mem_earn_amount; ?></td>
<td>₹<?php echo $mem_min_payout; ?></td>
<td><?php echo $mem_payout_percent; ?>%</td>
<td><?php if($mem_price == '0.00'){ echo "Free"; }else{ echo "₹$mem_price"; } ?></td>
<td><span class="<?php echo $statusColor; ?>"><?php echo ucfirst($mem_status); ?></span></td>
<td>
<form method="post" action="">
<input type="hidden" value="<?php echo $mem_id; ?>" class="memid">
<input type="hidden" value="<?php echo $status; ?>" class="status">
<input type="hidden" value="memstatus" class="type">
<?php if($mem_id != 1){ ?>
<input type="submit" class="btn <?php echo $btn; ?> mbslist" value="<?php echo ucfirst($btnVal); ?>">
<?php } ?>
Edit
</form>
</td>
</tr>
<?php $i++; } ?>
</table>
</div>
</div>
</div>
<div class="message"></div>
</div>
AJAX Code
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
processes/memberships.php
<?php
include('../../config/db.php'); include('../../functions.php');
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
Modify your processes/memberships.php with following code:
$memid = (!empty($_POST['id']))?$_POST['id']:null;
$type = (!empty($_POST['type']))?$_POST['type']:null;
$status = (!empty($_POST['status']))?$_POST['status']:null;
$color = (!empty($_POST['color']))?$_POST['color']:null;
$name = (!empty($_POST['name']))?$_POST['name']:null;
$capping = (!empty($_POST['capping']))?$_POST['capping']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
$minpay = (!empty($_POST['minpay']))?$_POST['minpay']:null;
$percent = (!empty($_POST['percent']))?$_POST['percent']:null;
$price = (!empty($_POST['price']))?$_POST['price']:null;
if($_POST){
if($type == 'memstatus'){
$update = $pdo->prepare("UPDATE memberships SET mem_status = :status WHERE mem_id = :id");
$update-> bindValue(':status', $status);
$update-> bindValue(':id', $memid);
$update-> execute();
if($update){
$pro = $pdo->prepare("SELECT * FROM memberships");
$pro-> execute();
$table = "<table class='table table-hover table-striped' id='mbslist'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Daily Capping</th>
<th>Commission</th>
<th>Payout</th>
<th>Payout %</th>
<th>Cost</th>
<th>Status</th>
<th>Action</th>
</tr>";
$i = 1;
while($p = $pro->fetch()){ extract($p);
if($mem_status == 'enabled'){
$statusColor = "text-success";
$btn = "btn-danger";
$status = "disabled";
$btnVal = "Disable";
}else{
$statusColor = "text-danger";
$btn = "btn-success";
$status = "enabled";
$btnVal = "Enable";
}
if($mem_price == '0.00'){ $mp = "Free"; }else{ $mp = $mem_price; }
$table .= "<tr>
<td>".$i."</td>
<td><span style='color: ".$mem_color."'>".$mem_name."</span></td>
<td>₹".$mem_daily_capping."</td>
<td>₹".$mem_earn_amount."</td>
<td>₹".$mem_min_payout."</td>
<td>".$mem_payout_percent."%</td>
<td>".$mp."</td>
<td><span class=".$statusColor.">".ucfirst($mem_status)."</span></td>
<td>
<form method='post' action=''>
<input type='hidden' value=".$mem_id." class='memid'>
<input type='hidden' value=".$status." class='status'>
<input type='hidden' value='memstatus' class='type'>
<input type='submit' class='btn ".$btn." mbslist' value=".ucfirst($btnVal).">
<a href='?mem=".$mem_id."&action=edit' class='btn btn-primary'>Edit</a>
</form>
</td>
</tr>";
$i++;
}
$table .= "</table>";
echo json_encode(array('status' => alert_success_dismiss("Membership has been ".$status."."), 'table' => $table));
}else{
echo json_encode(array('status' => alert_danger_dismiss("Server Error! Please refresh the page and try again.")));
}
}
}
?>
<script>
// Set Membership Status
$(document).ready(function(){
$(".mbslist").click(function() {
var dataString = {
id: $(this).closest('tr').find('.memid').val(),
type: $(this).closest('tr').find('.type').val(),
status: $(this).closest('tr').find('.status').val()
};
console.log(dataString);
$.ajax({
type: "POST",
dataType : "json",
url: "processes/memberships.php",
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$('.overlay').fadeIn();
},
success: function(json){
$('.message').html(json.status);
setTimeout(function(){
$('.overlay').fadeOut();
$('.message').fadeIn();
$('#mbslist').html(json.table).fadeIn();
}, 2000);
}
});
return false;
});
});
</script>
Hope this might help you.
Your submit button will try to submit form normally when you click it. So just use "event.preventDefault() " as below so your button wont trigger normal form submission and now wont load the page.
$(".mbslist").click(function(event) {
event.preventDefault();
}
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.
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);
}
}
?>
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');
});
I have a litte problem with the update. I have a couple of forms (over a loop). The script works fine with the first form, but with the others there is a problem.
while ($zeile = mysqli_fetch_array( $result, MYSQL_ASSOC))
{
....
$_SESSION['date'][$a] = $zeile['submit_time'];
$_SESSION['bes'][$a] = $zeile['date'];
<form id="upload" method="post" name="form">
<td>
<input onclick="this.value='';" class="datepicker" type="text" name="date" value="<?php echo $date_bes; ?>"/ readonly></td>
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
<td style='text-align:center;width:120px;'>
<input id="chk<?php echo $a; ?>" class="chk" name="chk" type="checkbox" value=""
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
<input type="hidden" class="id" value="<?php echo $id_submit; ?>">
</td>
<td style="text-align:center;width:240px;">
<textarea id="remark<?php echo $a; ?>" class="remark" name="remark" cols="30" rows="1" ><?php echo $remark; ?></textarea>
</td>
<td>
<input class="submit" type="image" src="save.jpg"></td>
</form>
...
}
my ajax_script.js
$(document).ready(function() {
$( "#upload" ).on("submit", function(e) {
e.preventDefault();
var id = $('.id').val();
var date = $('.datepicker').val();
var chk = $('.chk').prop('checked');
var remark = $('.remark').val();
$.ajax({
type: 'POST',
url: 'update.php',
data: {id: id, date: date, chk: chk, remark: remark},
success: function (data) {
if(data.success == true)
{
console.log('everything fine');
}
},
error: function(){
console.log('something bad happened');
}
});
alert('Job done');
});
});
and the update.php
<?php
$id = $_POST['id'];
$date = $_POST['date'];
$chk = $_POST['chk'];
$cancel_bool = ((int)$chk) ? 1 : 0;
$remark = $_POST['remark'];
$year = substr($date,6,4);
$mon = substr($date,3,2);
$day = substr($date,0,2);
$date = $year.'-'.$mon.'-'.$day;
if($chk == "true"){
$chk = 1;
}else{
$chk = 0;
}
echo "<br>";
echo $id ."<br>".$date."<br>".$chk."<br>".$remark;
require_once('config.php');
$link = mysqli_connect (
MYSQL_HOST,
MYSQL_USER,
MYSQL_PASSWORD,
MYSQL_DATABASE
);
if(!$link){
die('connection failed: ' .mysql_error());
}
$sql = "UPDATE table1
SET date = '$date', cancel_bool ='$chk', remark = '$remark' WHERE id_submits = $id";
$result = mysqli_query( $link, $sql );
?>
With the first form it posts the following param by clicking on save.jpg:
chk true
date 16.04.2014
id 1396002713.9412
remark mytext_one
second form:
chk
date 08.04.2014
remark mytext_two
Where is the id?
Any help or idea?
Greets Yab86