I am sending dynamically created form fields to CodeIgniter via ajax.
<div class="form-element">
<input type="radio" id="delete-radio[1]" name="delete-radio[1]" value="1">
</div>
<div class="form-element">
<label for="member_id[1]">Membership ID</label>
<input type="text" id="member_id[1]" name="member_id[]" autocomplete="off" value="<?php echo set_value('member_id[1]'); ?>"/>
<?php echo form_error('member_id[1]', '<div class="error">', '</div>'); ?>
</div>
<div class="form-element">
<label for="member_name[1]">Name</label>
<input type="text" id="member_name[1]" name="member_name[]" autocomplete="off" value="<?php echo set_value('member_name[1]'); ?>"/>
<?php echo form_error('member_name[1]', '<div class="error">', '</div>'); ?>
</div>
<div class="form-element">
<label for="member_address[1]">Address</label>
<input type="text" id="member_address[1]" name="member_address[]" autocomplete="off" value="<?php echo set_value('member_address[1]'); ?>"/>
<?php echo form_error('member_address[1]', '<div class="error">', '</div>'); ?>
</div>
I use the following to send them to their controller:
$('#submit').click(function() {
var form_data = $('#ajax-form').serialize();
alert(form_data);
$.ajax({
url: "<?php echo site_url('ajax_ci/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#form-name').append(msg);
}
});
return false;
});
Here is the controller:
if ($this->input->is_ajax_request()) {
$this->form_validation->set_rules('member_id[]', 'member ID', 'trim|required|xss_clean');
$this->form_validation->set_rules('member_name[]', 'member name', 'trim|required|xss_clean');
$this->form_validation->set_rules('member_address[]', 'member password', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
// connect to database
}
} else {
echo "Work on it! Don't give up!";
}
The screenshot below is currently what happens.
But I want these errors to appear in their respective individual form_errors
Is this possible in my current setup?
In the validation errors that you return from the server, you will need to include information about which field failed. Probably an array of (fieldname=>errormsg). Your ajax response handler can then find the correct field and append the message to the DOM accordingly.
Related
I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
There is, among others an "Edit account information" form, which has an image upload field. In the controller, the update() method contains the logic for the image upload action:
public function update() {
// Only logged in users can edit user profiles
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$id = $this->input->post('id');
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['author'] = $this->Usermodel->editAuthor($id);
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
// Upload avatar
$config['upload_path'] = './assets/img/avatars';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '100';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$uerrors = array('uerrors' => $this->upload->display_errors());
$data['uerrors'] = $uerrors;
}
if(!$this->form_validation->run() || !empty($uerrors))
{
print_r($data['uerrors']);
$this->load->view('partials/header', $data);
$this->load->view('dashboard/edit-author');
$this->load->view('partials/footer');
} else
{
$this->Usermodel->update_user($id);
$this->session->set_flashdata('user_updated', 'Your account details have been updated');
redirect(base_url('/dashboard/manage-authors'));
}
}
The (surprising) problem I have is that, even though I am uploading an image, print_r($data['uerrors']); returns You did not select a file to upload. in the browser.
In the view, the same error is returned:
<?php echo form_open(base_url('dashboard/users/update')); ?>
<input type="hidden" name="id" id="uid" value="<?php echo $author->id; ?>">
<div class="form-group <?php if(form_error('first_name')) echo 'has-error';?>">
<input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo set_value('first_name', $author->first_name); ?>" placeholder="First name">
<?php if(form_error('first_name')) echo form_error('first_name'); ?>
</div>
<div class="form-group <?php if(form_error('last_name')) echo 'has-error';?>">
<input type="text" name="last_name" id="last_name" class="form-control" value="<?php echo set_value('last_name', $author->last_name); ?>" placeholder="Last name">
<?php if(form_error('last_name')) echo form_error('last_name'); ?>
</div>
<div class="form-group <?php if(form_error('email')) echo 'has-error';?>">
<input type="text" name="email" id="email" class="form-control" value="<?php echo set_value('email', $author->email); ?>" placeholder="Email">
<?php if(form_error('email')) echo form_error('email'); ?>
</div>
<div class="form-group <?php if(form_error('bio')) echo 'has-error';?>">
<textarea name="bio" id="bio" cols="30" rows="5" class="form-control" placeholder="Add a short bio"><?php echo set_value('bio', $author->bio); ?></textarea>
<?php if(form_error('bio')) echo form_error('bio'); ?>
</div>
<input type="hidden" name="avatar" id="avatar" value="<?php echo $author->avatar; ?>">
<label for="avatar">Upload avatar</label>
<div class="form-group">
<input type="file" name="userfile" id="uavatar" size="20">
<p><?php print_r($uerrors); ?></p>
</div>
<div class="form-group">
<div class="w-50 pull-left pr-1">
<input type="submit" value="Update" class="btn btn-block btn-md btn-success">
</div>
<div class="w-50 pull-right pl-1">
Cancel
</div>
</div>
<?php echo form_close(); ?>
The error message I was expecting, considering that the image I was trying to upload is larger then the specified limit (100KB) is: The file you are attempting to upload is larger than the permitted size.
What am I doing wrong?
Try this
<?php echo form_open_multipart(base_url('dashboard/users/update')); ?>
<div class="form-group">
<input type="file" name="userfile" id="userfile" size="20">
<p><?php print_r($uerrors); ?></p>
</div>
Try to change your form opening, from :
<?php echo form_open(base_url('dashboard/users/update')); ?>
to
<?php echo form_open_multipart(base_url('dashboard/users/update')); ?>
To change the form encoding type from text/plain to multipart/form-data to support image data upload. Here is the difference between each encoding type.
please help me i would like to delete some check box if checkbox unchecked.
My checkbox is automatic show from database my sql. and i would like to delete some checkbox when checkbox in not checked.
PLease Help
its my controller
public function edit_overview($id_product)
{
if ($this->input->post('submit')) {
foreach ($id_overview = $this->input->post('id_overview') as $rm) {
$check_idoverview = $this->Biostar->check_idoverview($id_product, $rm);
if ($check_idoverview==unchecked){
$data['file'] = $check_idoverview;
$this->Biostar->delete_overview($check_idoverview,$id_product);
}else{
if ($check_idoverview > 0) {
} else {
$datafield = array(
'id_product' => $id_product,
'id_overview' => $rm
);
$this->Biostar->saveoverviewproduct($datafield);
$message_success = "Data Has Been Update";
}
}
}
}
$data['message_success'] = #$message_success;
$field = $this->Biostar->get_overview($id_product);
$fieldid_product = $this->Biostar->get_id_product($id_product);
$data['field'] = $field;
$data['id_product'] = $fieldid_product;
$data['content'] = "biostar/edit_overview_product";
$this->load->view('dashboard/index', $data);
}
My Model
function delete_overview($check_overview,$id_product)
{
$sql = "delete from overview_briostar where id_overview='$check_overview' AND id_product='$id_product'";
return $sql;
}
My View
<form method="post" action="<?php echo base_url(); ?>biostar/add_overview_product/<?php echo $id_product->id_product; ?>">
<div class="box-body">
<?php foreach ($speed as $row){ ?>
<div class="checkbox">
<label>
<input type="checkbox" name="id_overview[]" onClick="EnableSubmit3(this)" value="<?php echo $row['id_overview']; ?>"<?php foreach ($field as $wor){ ?> <?php if($row['id_overview']==$wor['id_overview']) echo "checked";?> <?php } ?> ><?php echo $row['title']; ?>
</label>
</div>
<?php } ?>
<!-- /input-group -->
</div>
<div class="box-footer">
<input value="Submit" type="submit" id="submit3" name="submit" class="btn btn-primary">
</div>
</form>
Unchecked checkbox value will not get posted, so you have to use jquery and ajax
Your checkbox
<input class="id_overview" type="checkbox" name="id_overview[]" value="<?php echo $row['id_overview']; ?>"<?php foreach ($field as $wor){ ?> <?php if($row['id_overview']==$wor['id_overview']) echo "checked";?> <?php } ?> ><?php echo $row['title']; ?>
your jquery
<script type="text/javascript">
$(document).ready(function() {
$("form#frm").submit(function(e) { // give a id to your form
e.preventDefault();
var ids = new Array();
$('.id_overview').each(function() {
if ($(this).is(':checked')) {
} else {
ids.push($(this).val());
}
});
$.ajax({
// send ids through your ajax code
});
});
});
</script>
create a new function and call it by ajax to delete the ids.
You can try like this
<form method="post" action="<?php echo base_url(); ?>biostar/add_overview_product/<?php echo $id_product->id_product; ?>">
<div class="box-body">
<?php foreach ($speed as $row){ ?>
<div class="checkbox">
<label>
<input type="hidden" name="all_id[]" value="<?php echo $row['id_overview']; ?>" />
<input type="checkbox" name="id_overview<?php echo $row['id_overview']; ?>" onClick="EnableSubmit3(this)" value="<?php echo $row['id_overview']; ?>"<?php foreach ($field as $wor){ ?> <?php if($row['id_overview']==$wor['id_overview']) echo "checked";?> <?php } ?> ><?php echo $row['title']; ?>
</label>
</div>
<?php } ?>
<!-- /input-group -->
</div>
<div class="box-footer">
<input value="Submit" type="submit" id="submit3" name="submit" class="btn btn-primary">
</div>
</form>
and in you controller
if ($this->input->post('submit')) {
foreach($all_id as $row_id)
{
if($this->input->post('id_overview'.$row_id))
{
//do action where id is present
}
else
{
//do action if unchecked by getting id $row_id
}
}
}
I dont know what am i doing wrong with the validation.
here is my Controller
function update_user() {
$this->load->library('form_validation');
$this->form_validation->set_rules('sirname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
$this->form_validation->set_rules('name', 'Last Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email');
if ($this->form_validation->run() == FALSE)
{
// fails
$this->load->view('update_view');
}
else
{
$data = array(
'surname' => $this->input->post('sirname'),
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
);
$this->Account_model->update_user(31,$data);
$this->show_user();
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Updated!</div>');
redirect('home');
}
}
here is my view
<form method="post" action="<?php echo base_url() . "account/update_user"?>" >
<div class="form-group">
<label for="name">First Name</label>
<input class="form-control" name="sirname" placeholder="Your First Name" type="text" value="<?php echo $user->surname; ?>" />
<span class="text-danger"><?php echo form_error('sirname'); ?></span>
</div>
<div class="form-group">
<label for="name">Last Name</label>
<input class="form-control" name="name" placeholder="Last Name" type="text" value="<?php echo $user->name; ?>" />
<span class="text-danger"><?php echo form_error('name'); ?></span>
</div>
<div class="form-group">
<label for="email">Email ID</label>
<input class="form-control" name="email" placeholder="Email-ID" type="text" value="<?php echo $user->email; ?>" />
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<button name="submit" type="submit" class="btn btn-default" onclick="account.php">Update</button>
<button name="cancel" type="reset" class="btn btn-default">Cancel</button>
</div>
<?php echo form_close(); ?>
<?php endforeach; ?>
<?php echo $this->session->flashdata('msg'); ?>
i need to display the value already in the database as im doing an update info for user.. so how do i implement the set_value('name') as well.
First preference is for form_error(),
so in value for each input fields,
value="<?php form_error("surname") ? echo set_value("surname") : echo $user->surname; ?> ?>"
Which means, if form error, then echo set_value() else echo database value.
in home controller where you redirect to success load :
$this->load->library('form_validation');
it will be ok!
You can use CI's built-in set_value function, which lets you set the values of a form field. It has a second (optional) parameter, to set the default value for the field.
<? echo form_label('Last Name', 'name'); ?>
<input class="form-control" name="name" id="name" type="text" value="<? echo set_value('name', $user->name) ?>">
<? echo form_error('name', '<span class="text-danger">','</span>');?>
In the code above, when loaded for the first time, the form will show the value from the database. But when returned after failing form validation, it will show the user input.
i have a form that insert in dbase what i write
here is the form,
<form id="contact-form" class="bl_form text-center" action="<?php echo "index.php?page=rooms&room=$rid&rpw=$rpw&r=$r";
?>" method="post" novalidate>
<span class="field-wrap scrollimation fade-right">
<input type="hidden" id="contact-name" name="contactName" type="text"
class="label_better requiredField" data-new-placeholder="Name" placeholder="Name" value="<?php echo "$uid"; ?>" data-error-
empty="*Enter your name">
</span>
<span class="field-wrap scrollimation fade-left">
<label class="control-label" for="contact-message">Message</label>
<textarea id="contact-message" name="message" rows="1" class="label_better
requiredField" data-new-placeholder="Message" placeholder="Message" data-error-empty="*Enter your message"></textarea>
</span>
<p class="text-center"><button name="sy2" id="submit_post" type="submit" class="btn btn-meflat
icon-left" data-error-message="Error!" data-sending-message="Sending..." data-ok-message="Message Sent"><i class="fa fa-paper-
plane"></i>Send Message</button></p>
<input type="hidden" name="submitted" id="submitted" value="true" />
<?php echo "<postfield name=\"message\" value=\"$(message)\"/>"; ?>
</form>
and i want to put a ajax code that display this message from dbase
<?php echo make_clickable($tosay)."$link_delete"; ?>
Can someone provide me an example?Thank you
Look at this
Ajax tutorial for post and get
So, the jQuery
$('body').on('submit', '#contact-form', function(){
$.post({$(this).attr("action"), $(this).serialize(), function(data){
if(data){
alert(data.message);
}
}, 'json');
return false;
});
And the server side
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// do your thing here
echo json_encode(array("message" => make_clickable($tosay).$link_delete));
die();
}
?>
I am using codeigniter. Below is the code for my registration page.
Controller
function register()
{
$this->load->library('form_validation');
$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('username', 'Username', 'trim|required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('user_email', 'Email', 'trim|required|valid_email|is_unique[users.user_email]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('ans_1', 'Security answer 1', 'required');
$this->form_validation->set_rules('ans_2', 'Security answer 2', 'required');
if($this->form_validation->run() == FALSE) {
//not validated - reload the view and display errors
$this->load->database();
$this->load->model('user');
$data['ques'] = $this->user->get_que();
$this->load->view('register',$data);
}
else {
$this->load->database();
$this->load->model('user');
//create user
$this->user->create_user();
$this->thank();
}
}
View
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<link rel="stylesheet" href="http://localhost/cinema/assets/css/form.css">
</head>
<body>
<form action="http://localhost/cinema/login/register" method="post" accept-charset="utf-8" class="username register" >
<h3>User Registration form:</h3>
<p><label for="first_name">First Name</label>
<input type="text" name="first_name" /></p>
<p><label for="last_name">Last Name</label>
<input type="text" name="last_name" /></p>
<p><label for="username">Username</label>
<input type="text" name="username" /></p>
<p><label for="user_email">Email</label>
<input type="text" name="user_email" /></p>
<p><label for="password">Password</label>
<input type="password" name="password" /></p>
<br><font size='4'>Select security question 1:</font>
<select name="que_1">
<?php
foreach($ques as $que)
{
echo '<option value="'.$que->que_ID.'">'.$que->que.'</option>';
}
?>
</select><br><br>
<p><label for="ans_1">Answer:</label>
<input type="text" name="ans_1" /></p>
<br><font size='4'>Select security question 2:</font>
<select name="que_2">
<?php
foreach($ques as $que)
{
echo '<option value="'.$que->que_ID.'">'.$que->que.'</option>';
}
?>
</select><br><br>
<p><label for="ans_2">Answer:</label>
<input type="text" name="ans_2" /></p>
<input type="submit" name="btnSubmit" class="styled-button-8" style="float:right; margin-right:300px; margin-top:-10px;" value="Sign Up!"
/>
<font color="red" size="4"><b>
<?php echo validation_errors(); ?></b></font>
</form>
</body>
</html>
<br>
My problem is that in case the user fills invalid data and clicks the signup button, the page is refreshed and the validation errors are displayed but the data entered by the user doesn't remain there.He has to again fill the whole form. I want the user data to be retained and displayed in this case. Thanks in advance .. :)
For this you need set_value()
For input fileds
<input type="text" name="last_name" value='<?php echo set_value('last_name')?>'/>
This will get the value from $_POST and print after failed validation. Also takes 2nd parameter as default value.
<?php echo set_value('last_name','John')?>
Read the Form Helper Class.
You can try like this. You can maintain session to display user fields data while validation check. I added a Sample with session in your form.
Your View :
<?php session_start(); ?>
<form action="http://localhost/cinema/login/register" method="post" accept-charset="utf-8" class="username register" >
<h3>User Registration form:</h3>
<p><label for="first_name">First Name</label>
<input type="text" name="first_name" value="<?php echo $_SESSION['first_name']; ?>" /></p>
<font color="red" size="4"><b>
<?php echo validation_errors(); ?></b></font>
</form>
Your controller:
function register() {
$this->load->library('form_validation');
$firstName = $this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
$this->session->set_userdata('first_name', $firstName);
if ($this->form_validation->run() == FALSE) {
//redirect to register page
} else {
//register user details
$this->session->unset_userdata('first_name');
}
Better solution is : use post data
<input type="text" name="last_name" value='<?php echo $this->input->post('last_name')?>'/>
When you use set_value(), you must send that field to validation even it is not required.
But for Post, you don't want to do any additional work.
In your controller put a data array and pass the user entered values to that.Then if there are form validation errors pass those data to the view.
In the view use CI set_value() method to show the previous entered values.