I got a website delivered to me, and the dev doesn't reply to me anymore. As a beginner I am trying to find a solution by my own but I can't figure it out.
I would like to add a feature and maybe you guys can help me.
To explain our users can write some comments on a single page, before to be published our moderator is validating the comment, as soon as it is done the user is receiving an email saying your comment Blablabla has been validated.
We would like to add to the email a link to the page where he wrote his comment, as we have a lot of single pages with different URL, it will be easier for him to found his comment back.
So our goal is to save the URL into the database and then I will extract that URL to put it in the email.
I have added in the our user_comment DB the column url_link to store the URL.
Here is my controller, I have added urllink
public function add_comment(){
if ($this->session->userdata('user_id')){
$comment = $this->security->xss_clean($this->input->post('comment'));
$pageid = $this->security->xss_clean($this->input->post('page_id'));
$urllink = $this->security->xss_clean($this->input->post('url_link'));
$data = array(
'user_id' => $_SESSION['user_id'],
'page_id' => $pageid,
'url_link' =>$urllink,
'comment' => $comment,
'created' => date("Y-m-d H:i:s"),
'modified' => date("Y-m-d H:i:s")
);
echo $query = $this->page_model->add_comments($data);die;
}else{
redirect();
}
}
My model
public function add_comments($data){
if($this->db->insert('user_comment',$data)){
return 'true';
}else{
return 'false';
}
}
My view for the comment section
<h3>Post a Comment</h3>
<?php if ($this->session->userdata('user_id')){?>
<div class="textarea_editor" style="clear:left; ">
<div class="textarea_editorinner">
<div id="editor" data-id="<?php if(!empty($_SESSION['user_id'])){ echo $_SESSION['user_id'];}else{ echo '';}?>"></div>
<textarea name="comment" style="display:none" id="hiddenArea" class="add_comment"></textarea>
</div>
<?php }else{?>
<div class="write-comment">
<input style="margin-left:10px; " type="text" data-toggle="modal" data-target="#user_login" placeholder="Type your comment" class="add_comment">
<?php }?>
<?php
if ($this->session->userdata('user_id')){?>
<button class="sendmessage sendmessageclick" data-d-id="<?php echo $pages[0]->pageId;?>"><span class="far fa-paper-plane">
</span><span class="d-none d-block-sm">Send</span></button>
<?php }?>
</div>
</div>
My common.js
$('.sendmessageclick').click(function(){
$('#hiddenArea').val(quill.container.firstChild.innerHTML);
$.ajax({
type:'post',
async: false,
data:{page_id:$(this).attr('data-d-id'),comment:$('.add_comment').val()},
url: static_url+'/pages/add_comment',
success: function(result){
$('.add_comment').val('');
if(result == 'true'){
$('.comment_alert').show();
setTimeout(function() {
$('.comment_alert').hide();
location.reload();
}, 3000);
}else{
alert('Error');
location.reload();
}
console.clear();
}
});
});
Everything is working perfectly, except URL, for sure I am missing something to indicate the URL to be stored in the DB.
Thanks for your support.
As I can see your controller collect three POST variables they are 'comment', 'page_id', and 'url_link'. However, if you look at your view code only 'comment' is sent.
A simple solution would be to add two additional input boxes having the name 'page_id', and 'url_link'.
<h3>Post a Comment</h3>
<?php if ($this->session->userdata('user_id')){?>
<div class="textarea_editor" style="clear:left; ">
<div class="textarea_editorinner">
<div id="editor" data-id="<?php if(!empty($_SESSION['user_id'])){ echo $_SESSION['user_id'];}else{ echo '';}?>"></div>
<textarea name="comment" style="display:none" id="hiddenArea" class="add_comment"></textarea>
<input type='hidden' name='page_id' value='<<Page ID value added by PHP>>'>
<input type='text' name='url_link' value=''>
</div>
<div class="write-comment">
<input style="margin-left:10px; " type="text" data-toggle="modal" data-target="#user_login" placeholder="Type your comment" class="add_comment">
<?php }?>
<?php
if ($this->session->userdata('user_id')){?>
<button class="sendmessage sendmessageclick" data-d-id="<?php echo $pages[0]->pageId;?>"><span class="far fa-paper-plane">
</span><span class="d-none d-block-sm">Send</span></button>
<?php }?>
</div>
</div>
Related
I am working on a codeigniter 3 app and ive recently implemented a session checker that deletes a user session if they're already logged in. Now we want a modal box to pop up if the user is already logged in with another session. I am able to get a modal box to pop up using a button but i want to implement it into the original flow of the login system. As it is the login form takes you straight to the validate login system. This is the login form now:
<form action="<?php echo site_url('login/validate_login/user'); ?>" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
The button at the moment goes straight to this login function:
public function validate_login($from = "") {
$email = $this->input->post('email');
$password = $this->input->post('password');
$credential = array('email' => $email, 'password' => sha1($password), 'status' => 1);
// Checking login credential for admin
$query = $this->db->get_where('users', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('user_id', $row->id);
$this->session->set_userdata('role_id', $row->role_id);
$this->session->set_userdata('role', get_user_role('user_role', $row->id));
$this->session->set_userdata('name', $row->first_name.' '.$row->last_name);
$this->delete_session_user_id();
$this->session->set_flashdata('flash_message', get_phrase('welcome').' '.$row->first_name.' '.$row->last_name);
if ($row->role_id == 1) {
$this->session->set_userdata('admin_login', '1');
redirect(site_url('admin/dashboard'), 'refresh');
}else if($row->role_id == 2){
$this->session->set_userdata('user_login', '1');
$this->set_session_user_id();
redirect(site_url('home/my_courses'), 'refresh');
}
}else {
$this->session->set_flashdata('error_message',get_phrase('invalid_login_credentials'));
redirect(site_url('home/login'), 'refresh');
}
}
I created this function to pull the user id from the emails:
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
This function can get the user id based on the email supplied.
Then I use this function to check if there is a session and return false if there are 0 results and true if there is a session with that user id. So if its false they should be able to log in and the modal pop-up shouldnt open but if its true it should open.
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
I think this is the best approach without having to redo the entire login flow. Perhaps someone can advise if this is the best approach or if in fact i should change the entire flow.
Thanks
Here is the previous problem I had which I have answered myself
https://stackoverflow.com/questions/62458226/codeigniter-3-stop-multiple-logins-using-ci-sessions-database
UPDATE Added to clarify my problem
Well the problem is when a login is attempted from another device it should logout the other active session. So if o logged in on my desktop in a new browser or even my phone with the same user ID the active session should end, at the moment it does so without warning the user. So I want to have a modal pop up warning the user that there is an active session currently running with this user id
You need to implement an Ajax call which will check whether the user is already logged in or not. If the user is not logged In than you can proceed to login otherwise trigger your popup open to display the message.
Here the user has choices to log in or not, If users choose to login then you can unbind the event on submit and let the user go ahead.
I have made some changes to your HTML file. Please check below -
Your HTML template
<form action="<?php echo site_url('login/validate_login/user'); ?>" id="login-form" onSubmit="return checkUserSession();" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="button" id="modal-submit-button" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
<script>
/** Trigger function on form submit whether to check user logged in */
function checkUserSession(){
var email = $("#login-email").val();
$.ajax({
url: "<?php echo site_url('login/checkUserSession'); ?>",
type: 'POST',
data: { 'email': email},
success: function(status){
if(status == true) { // User is already logged in somewhere, display the messege.
$("#login").modal();
return false;
} else { // User is not logged in, submit the form
return true;
}
}
});
}
/** Allow user to log in with exception */
$("#modal-submit-button").on("click", function(){
$("#login").modal('hide'); // hide the modal
$("#login-form").attr("onSubmit", ""); // unbind the function
$("#login-form").submit(); // submit login form
})
</script>
Controller -
<?php
/** Function to check user logged in or not */
public function checkUserSession() {
$user_email = $this->input->post('email');
$userId = $this->get_user_id($user_email);
$response = $this->user_has_session($userId);
echo $response;
}
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
?>
I'm developing a web application, and I want to pass variable called ID when the form method is post that linked to open other form but in the config/routes I'm using $routes[page_A][get] = 'Controller' not $routes[page_A][post] = 'Controller'.
I'm using Codeigniter framework here, I've tried to change the controller with $this->input->get('id') but it doesn't work and I don't have any idea whats really happen in my codes.
The Sender Form View code
<form action="<?= base_url().'progres_save'; ?>" method="POST">
<div class="form-group">
<div class="form-row">
<label for="idJobOrder">ID Job Order</label>
<input type="text" name="idJobOrder" class="form-control" value="<?php echo $rd[0]->kodejobglobal; ?>" readonly>
</div>
</div>
<div class="form-group">
<div class="form-row">
<a class="btn btn-primary col-xl-1 col-sm-1 mb-1 ml-auto mr-0 mr-md-2 my-0 my-md-3" href="job" id="back" role="button"><i class="fas fa-fw fa-arrow-left"></i> Back</a>
<button class="btn btn-primary btn-block col-xl-1 col-sm-1 mb-1 mr-0 mr-md-2 my-0 my-md-3">Save <i class="fa fa-fw fa-arrow-right"></i></button>
<input type="hidden" name="id" value="<?php echo $rd[0]->kodejobspesifik ?>">
</div>
</div>
</form>
The Sender Form Controller code
public function save()
{
$idglobal = $this->input->post('idJobOrder');
$data = array('jobnya' => $idglobal );
$this->Model_joborder->save_pg($data,'lapharian');
redirect('progres_material');
}
The Config Routes code
$route['progres_save']['get']='error';
$route['progres_save']['post']='save';
$route['progres_material']['get']='matused';
$route['progres_material']['post']='error';
The Recipient Form Controller code
public function matused()
{
$id = $this->input->get('id');
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
The Recipient Form View code
<form method="POST" action="<?= base_url().'matsave'; ?>">
<div class="form-group">
<div class="form-row">
<?php if (isset($rd[0])) {?>
<input type="hidden" value="<?php echo $rd[0]->jobspesifiknya; ?>" name="idClient" class="form-control" placeholder="First name" readonly>
<?php } ?>
</div>
</div>
</form>
What I expect is the input id value from Sender will be passed and catch on Recipient form as input idClient. Can anyone her help me to find out the solution? Thank you.
You can use PHP global variable $_REQUEST to capture the data if you are not sure about the request type like this,
public function matused()
{
$id = $_REQUEST['id'];
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
You forgot to include the id data on the redirect after the save() method is called, so you will not get anything by calling $this->input->get('id').
To solve this, pass the id data along with the redirect :
redirect('progres_material?id=' . $this->input->post('id'));
But that of course it will gives you an extra parameter on the url. If you don't want additional parameter, you could alternatively use session to pass id data while redirecting, on CodeIgniter there is a method called set_flashdata to do this :
$this->session->set_flashdata('id', $this->input->post('id'));
redirect('progres_material');
And to get the id session data on the matused() method, use the following code :
$id = !empty($this->session->flashdata('id')) ? $this->session->flashdata('id') : $this->input->get('id');
html code
<form>
<div class="list">
<div class="list list-inset" >
<label class="item item-input" id="descriptions">
<input type="text" height:"90" class="description" placeholder="Description ..." ng-model="data.describe" required>
</label>
<label input="email" class="item item-input" id="email" ng-model="data.email" required >
<span class="input-label">Email</span>
<input type="email">
</label>
<label class="item item-input">
<span class="input-label">Date</span>
<input type="date">
</label>
</div>
<button class="button button-block button-balanced" type="submit" ng-click="AddItem(); submitForm()">
Add Item
</button>
<button class="button button-block button-assertive" ng-click="closeModal()"> cancel</button>
</div>
</form>
app.js
$scope.data = {
description: "default",
email: "default",
date: "default",
};
$scope.submitForm = function() {
console.log("posting data....");
$http.post('http://localhost:4400/api.php', JSON.stringify($scope.data)).success(function () {/*success callback*/ });
};
api.php
<?php
$name=$_POST['descriptions'];
$email=$_POST['email'];
$message=$_POST['date'];
if (($descriptions =="")||($email=="")||($date==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $descriptions<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form" + $date;
mail("testing#gmail.com", $subject, $message, $from);
echo "Email sent!";
}
?>
I am trying to send contents of a form to an email address provided. The problem is when I try and do this, I get an error: POST http://localhost:4400/api.php 404 (Not Found). I have looked on other posts and cannot resolve this issue thank you.
enter image description here
use http://localhost:4400/api.php instead of api.php at your code
and change submit like this
<form action="api.php" method="post" id="myform" name="myform">
and
<button onclick="document.getElementById("myform").submit()">SUBMIT</button>
You can link your php file with a relative url. If your file api.php is in app/, you can write in your app.js :
$scope.submitForm = function() {
$http.post('api.php', JSON.stringify($scope.data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
};
In api.php :
$descriptions = $_POST['descriptions'];
$email = $_POST['email'];
$date = $_POST['date'];
I'm click my submit button freely without enter values in the form..then in my database a row inserted that columns contain zeros
controller
function submit_expense()
{
$exp_date=$this->input->post('expense_date');
$expense_ids= $this->input->post('expense');
$expense_ids=substr($expense_ids,0,strlen($expense_ids)-1);
$expense_id_array = explode(',',$expense_ids);
$id=$this->session->userdata('userid');
for($i=0;$i<count($expense_id_array);$i++)
{
$required_id = TRIM($expense_id_array[$i]);
$this->form_validation->set_error_delimiters('<div style="color:#B94A48">', '</div>');
$this->form_validation->set_rules('exp_amount_'.$required_id, 'Expense Amount', 'required|numeric');
$this->form_validation->set_rules('comment_'.$required_id, 'Comments', 'required|alpha');
if ( $this -> form_validation -> run() === FALSE )
{
$this->index();
}
else
{
$amount= $this->input->post('exp_amount_'.$required_id);
$comment=$this->input->post('comment_'.$required_id);
$expense_data=array(
'expense_id'=>$required_id,
'expense_amount'=>$amount,
'user_id'=>$id,
'date'=>$exp_date,
'comments'=>$comment,
);
$this->home_model->insert_expense($expense_data);
$this->session->set_flashdata('message', 'Successfully submitted.');
redirect(base_url().'home/index');
}
}
}
And also my validation is not working
footer_view
var new_String ='<div class="form-group" id="ex_'+unqid1+'">'
+'<label for="exampleInputPassword1">'+name+'</label> </br>'
+'<input name="exp_amount_'+unqid1+'" id="id_'+unqid1+'" type="text" '+
'class="form-control" placeholder="Enter '+name+' expense amount" style="margin-right:20px;" required>'
+'<input name="comment_'+unqid1+'" type="text" id="comment" class="form-con" placeholder="Comments" style="margin-right:20px;" required ></div >' ;
$("#create_exp").append(new_String);
view
this is my view use the id create_exp in my footer
<form role="form" action="<?echo base_url()?>home/submit_expense" method="post">
<?$todays_date=date('Y-m-d');?>
<input id="expense_date" name="expense_date" value="<?echo $todays_date;?>" type="hidden" />
<div class="red">
<? echo $this->session->flashdata('message'); ?>
</div>
<div class="box-body" id="create_exp">
<?php echo validation_errors(); ?>
<span>Choose from the right which all you need to enter for today</span>
<!--here goes the input boxes-->
<!-- /.input boxes -->
</div><!-- /.box-body -->
<span id="errmsg1"></span>
<input id="expenseVal" name="expense" type="hidden" class="form-control">
<div class="box-footer" id="button_id">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
As the OP Wants to show the all the Errors inside a div
<div id="error">
<?php echo validation_errors(); ?>
</div>
As the OP Wants some additional info,
To include a view or common page
$this->load->view('yourownpage');
Then you should have yourownpage.php inside your views folder
To have pagination, Have this in your controller's function
$this->load->library('pagination');
$config['base_url'] = 'yourownpage';
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
echo $this->pagination->create_links();
Note :
Make sure to place the error div in the place that didn't hurt your textbox
I have all my callback functions in My_Controller so that they are not repeated throughout the website. This works fine but for some reason one of my functions is not working when I am posting information using AJAX but is working on other pages. The message I get back when I use the callback is:
Unable to access an error message corresponding to your field name.
But then I've created a message for it using set_message() and it works fine on the other page without AJAX.
If you were interested in the log, here is the relevant output when entering an invalid date:
ERROR - 2013-05-24 16:03:08 --> -----Valid date format called, 223013-05-15
ERROR - 2013-05-24 16:03:08 --> -----Should be okay = , 223013-05-15
ERROR - 2013-05-24 16:03:08 --> -----Valid date format = false, 223013-05-15
And with a valid date:
ERROR - 2013-05-24 16:06:00 --> -----Valid date format called, 2013-05-24
ERROR - 2013-05-24 16:06:00 --> -----Should be okay = , 2013-05-24
ERROR - 2013-05-24 16:06:00 --> -----Valid date format = true, 05,24,2013
Here is the callback:
class MY_Controller extends CI_Controller
{
var $options;
public function __construct()
{
parent::__construct();
date_default_timezone_set('Europe/London');
$this->options->calendar = FALSE;
}
//Check date format aggainst mysql format, valid dates only, no 30-2-2010.
function _Valid_Date_Format($date)
{
log_message('error', '-----Valid date format called, '.$date);
if( empty($date) )
{
$this->form_validation->set_message('_Valid_Date_Format', 'This date is required.');
return FALSE;
}
else
{
log_message('error', '-----Should be okay = , '.$date);
}
$parsed = explode('-',$date);
if( checkdate($parsed[1],$parsed[2],$parsed[0]) )
{
log_message('error', '-----Valid date format = true, '.$parsed[1].','.$parsed[2].','.$parsed[0]);
return TRUE;
}
log_message('error', '-----Valid date format = false, '.$date );
$this->form_validation->set_message('_Valid_Date_Format', 'The Date entered is invalid.');
return FALSE;
}
}
Here is the AJAX Code:
//Submit time feature
$("#submit_time").click(function()
{
var cct = $.cookie('csrf_simple_cookie');//Overcome ajax limitation with csrf function, see below:
$.ajax({
url: folder,
type:"POST",
context: document.body,
data: {t_id:$('#t_id').val(),
time_for:$('#time_for').val(),
hrs_spent:$('#hrs_spent').val(),
mins_spent:$('#mins_spent').val(),
timer_description:$('#timer_description').val(),
date_worked:$('#date_worked').val(),
csrf_simple_collab:cct},
dataType: "json",
error: function(XMLHttpRequest,error)
{
if(error=='parsererror')//Not logged in.
{
window.location.replace(loginFolder)//redirect to login page
}
},
success: function(data)
{
if(data.success)
{
var message=$('#message-box').html('<span>Time data added successfully.</span>').hide();
message.fadeIn("slow");
javascript:location.reload(true);
}
else
{
if(data.validation)
{
//var message=$('#message-box').html("<span>Database error</span>");
var message=$('#message-box').html(data.error);
}
else
{
var message=$('#message-box').html(data.error);
$('#time-for-error').html(data.time_for);
$('#date-worked-error').html(data.date_worked);
$('#mins-spent-error').html(data.mins_spent);
$('#hrs-spent-error').html(data.hrs_spent);
$('#timer-description-error').html(data.timer_description);
}
}
}
});
return false;
});
Here is the view:
<?
//If we are an admin we can alter the user the information is added for.
if($this->session->userdata('userType')=='admin'): ?>
<div class="form_row">
<div class="form_field">
<label for="time_for">User:</label>
</div>
<div class="form_field name_element" id="time-for-container">
<select name="time_for" id="time_for">
<?
foreach($users as $key => $u):
if($u->userId==$this->session->userdata('userId')):
?>
<option selected="selected" value="<?=$u->userId?>"><?=$u->userName?></option> <?='\n'?>
<?
else:
?>
<option value="<?=$u->userId?>"><?=$u->userName?></option> <?='\n'?>
<?
endif;
endforeach;
?>
</select>
<p id="time-for-error"></p>
</div>
</div>
<? else: ?>
<input type="hidden" id="time_for" name="time_for" value="<?=$this->session->userdata('userId')?>">
<? endif; ?>
<div class="form_row">
<div class="form_field">
<label for="hrs_spent">Hours and minutes spent:</label>
</div>
<div class="form_field name_element" id="mins-spent-container">
<input type="text" maxlength="6" name="hrs_spent" id="hrs_spent" value="" />
<span id="min-separator">:</span>
<input type="text" maxlength="6" name="mins_spent" id="mins_spent" value="" />
<p id="mins-spent-error"></p>
<p id="hrs-spent-error"></p>
</div>
</div>
<div class="form_row">
<div class="form_field">
<label for="date_worked">Date Worked:</label>
</div>
<div class="form_field name_element" id="date-picker-container">
<input type="text" name="date_worked" id="date_worked" />
<p id="date-worked-error"></p>
</div>
</div>
<div class="form_row">
<div class="form_field">
<label for="timer_description">Description:</label>
</div>
<div class="form_field name_element" id="description-container">
<textarea name="timer_description" id="timer_description" value=""></textarea>
<p id="timer-description-error"></p>
</div>
</div>
<input type="hidden" id="c_id" name="c_id" value="<?=$task->c_id ?>" />
<input type="hidden" id="p_id" name="p_id" value="<?=$task->p_id ?>" />
<input type="hidden" id="t_id" name="t_id" value="<?=$task->t_id ?>" />
<input type="hidden" name="login-folder" id="login-folder" value="<?=base_url()?>login" />
<input type="hidden" name="submit-folder" id="submit-folder" value="<?=base_url()?>times/submit_time" />
<div class="form_row">
<div id="message-box"></div>
<input type="button" name="submit" id="submit_time" class="button-styles button-three" value="Add time" />
</div>
</div>
Controller method:
class Times extends MY_Controller
{
var $options;
//Ajax function used to submit the time information from task page form.
function submit_time()
{
$options=array();
$this->form_validation->set_rules("time_for","Time for","trim|required|is_natural_no_zero");
$this->form_validation->set_rules("hrs_spent","Hrs spent","trim|required|is_natural|min_length[1]|max_length[5]");
$this->form_validation->set_rules("mins_spent","Mins spent","trim|required|is_natural|min_length[1]|max_length[2]|less_than[60]");
$this->form_validation->set_rules("timer_description","Description","trim|min_length[5]|max_length[1000]");
$this->form_validation->set_rules("date_worked","Date Worked","trim|required|callback__valid_date_format");
//$json->data=array('success'=>0,'validation'=>1,'error'=> validation_errors() );
//$this->load->view('data/json_encode',$json);
if($this->form_validation->run())
{
$options['hrs_spent'] = $this->input->post('hrs_spent');
$options['mins_spent'] = $this->input->post('mins_spent');
$options['timer_description'] = $this->input->post('timer_description');
$options['date_worked'] = $this->input->post('date_worked');
$options['t_id'] = $this->input->post('t_id');
$options['u_id'] = $this->input->post('time_for');//Notice time for field here.
$add = $this->time_model->add_time($options);
if(!$add):
$json->data=array('success'=>0,'validation'=>1,'error'=>'Database error');
else:
$json->data=array('success'=>1,'validation'=>1);
$this->log_model->add_log_entry( array('log_id'=>1,'item'=>'Time record "'.reduce_string($options['timer_description'],50).'" was added for user '.$options['u_id'].'.') );
endif;
$this->load->view('data/json_encode',$json);
}
else
{
$json->data = array(
'time_for' => form_error('time_for'),
'hrs_spent' => form_error('hrs_spent'),
'mins_spent' => form_error('mins_spent'),
'timer_description' => form_error('timer_description'),
'date_worked' => form_error('date_worked'),
'success'=>0,
'validation'=>0,
'error'=>'There are errors in the form.'
);
$this->load->view('data/json_encode',$json);
}
}
}
The problem is the capitalization used in the callback method name. The method name, and all subsequent references to it as a validation rule, should be all lowercase.
To explain, this is the relevant part of the Form Validation library that causes the message:
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
All of your set_message() calls name the rule as _Valid_Date_Format, which is the array key that exists in $this->_error_messages.
Because your rule is defined as _valid_date_format, and because PHP is case-sensitive most of the time, the isset() rule fails, and you clearly don't have a language line defined for it, so it goes to the default.
In general, using capitalization in your controller methods will cause problems. So it's best to avoid doing so.