Codeigniter offers you a tutorial to get to know it and how to use it. This tutorial teaches you to create elements in a table in a database, but doesn't teach you how to update this elements. I am trying to make an update query using the codeigniter libraries, but the form from de update view doesn't submit.
AT NEWS_MODEL:
public function update_news($slug)
{
$this->load->helper('url');
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
$this->db->where('slug', $slug);
$this->db->update('news', $data);
}
AT NEWS CONTROLLER:
public function update($slug)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Update a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
// The form was NOT posted
// So we load the view
$data['news_item'] = $this->news_model->get_news($slug);
$this->load->view('templates/header', $data);
$this->load->view('news/update', $data);
$this->load->view('templates/footer');
}
else
{
// The form was submitted
$data = array(
'title' => $this->input->post('title'), //-->post variable
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text')
);
$this->news_model->update_news($slug, $data);
$this->load->view('news/success');
}
}
AT UPDATE VIEW:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ;?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update news item" />
</form>
I've tested the code with "console.log()" and the problem seems to be that the form of the update view doesn't submit, but I cannot figure why, because the form is similar to the create form, which does work perfectly:
<h2><?php echo $title; ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create'); ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
your problem is :
you use === instead of == in this line:
if ($this->form_validation->run() === FALSE)
Related
I have a PHP code and JSON as shown below:
PHP Code:
<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
$output = array();
$output['en_desc']=$_POST['en_desc'];
$output['code']=$_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
}
?>
<?php if($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<input type="hidden" id="savechanges" name="savechanges" value="1">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
JSON:
{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
The following DOM is generated through the PHP/JSON code above:
DOM (HTML):
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
<input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
<input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.
JS code:
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
Problem Statement:
The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.
I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.
Step 1: User delete the row from the DOM on click of a delete button.
Step 2: On saving the form and rendering the page, that deleted row should not be present.
I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.
unset($data->code);
unset($data->en_desc);
You have a typo here:
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
it should be
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
Look at the "s" :)
Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:
<?php
if (isset($_POST['submit'])) {
$output = array();
$output['en_desc'] = $_POST['en_desc'];
$output['code'] = $_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}
?>
<?php if ($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit" name="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else {
echo 'Cannot read JSON settings file';
} ?>
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
I am trying to display a form error underneath the input fields but after I click the submit button it will redirect to another page...
Here's my code page controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends CI_Controller{
public function view($page = 'home'){
if(!file_exists(APPPATH.'views/pages/'.$page.'.php')){
show_404();
}
$data['title'] = ucfirst($page);
$this->load->view('template/header');
$this->load->view('pages/'.$page);
$this->load->view('template/footer');
}
public function login(){
echo $this->input->POST('username');
}
public function registercheck(){
echo $this->input->POST('username');
echo $this->input->POST('pwd');
echo $this->input->POST('pwd2');
echo $this->input->POST('fname');
echo $this->input->POST('position');
echo $this->input->POST('contactnumber');
$this->form_validation->set_rules('username', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd2', 'UPPERCASE', 'required|max_lenght[20]');
$this->form_validation->set_rules('fname', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('position', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('contactnumber', 'USERNAME', 'required|max_lenght[20]');
if($this->form_validation->run() == false){
$this->load->view('pages/register');
} else{
echo 'register ok';
}
}
}
?>
And here is my views/pages/register.php
<form action="<?php echo base_url(); ?>pages/registercheck" method="post">
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
</form>
Please help me..
What am I doing wrong?
Thank you in advance!
You are in the right direction. But to achieve the desire functionality, you should do as so:
The form and the input validation should be in the same page (controller). In your example, both should be in register.php.
This basic pseudo code should do the trick:
On register page controller:
If method == get:
Display register form.
If method == post:
Check the form data:
If errors exists:
display register page with error.
else:
redirect to ....
Good Luck!
I have a multiselect dropdown, which allows me to select more than one user at a time. I want to be able to select more than one user and when I click on the "Send code" button, the application will snow send email to these users using the email addresses. Currently when I select and click "Send Code", the application will only send email to only one user leaving other once. Please I will like to know to be sending email to all selected users at a time. I'm using CodeIgniter and below is my code:
Below is the view section of my code, which enable user to select users and send code:
<head>
<meta charset="UTF-8">
<title>Member Invite</title>
</head>
<body>
<form class="form-horizontal" method="post" action="<?php echo site_url('root/administrator/sendinvite'); ?>">
<fieldset>
<div class="control-group">
<label class="control-label" for="select01">Select Set</label>
<div class="controls">
<select id="select01" class="chzn-select" name="set_code" title="Select the set this student(s) will belong to">
<option value="">Select set</option>
<?php foreach ($sets as $set) { ?>
<option <?php echo set_select('set_code', $set->group_id); ?> value="<?php echo $set->group_id; ?>"><?php echo $set->group_name; ?></option>
<?php } ?>
</select>
<font size="1" color='red'><?php echo form_error('set_code'); ?></font>
</div>
</div>
<div class="control-group">
<label class="control-label" for="multiSelect">Select student(s)</label>
<div class="controls">
<select multiple="multiple" id="multiSelect" name="student_email" class="chzn-select span4" title="Select student(s) for this set">
<option value="">Select Student</option>
<?php foreach ($students as $student) { ?>
<option <?php echo set_select('student_email', $student->uacc_email); ?> value="<?php echo $student->uacc_email; ?>"><?php echo $student->uacc_username; ?></option>
<?php } ?>
</select>
<p class="help-block">Start typing to activate auto complete!</p>
<font size="1" color='red'><?php echo form_error('student_email'); ?></font>
</div>
<input type="hidden" name="student_id" value="<?php echo $student->upro_uacc_fk; ?>" class="span6 m-wrap"/>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Send code</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
</body>
</html>
Below is my Controller, which accepts the selected users and used same to send email:
public function sendinvite() {
if ($this->input->post()) {
$this->form_validation->set_rules('student_email', 'Student name', 'required');
$this->form_validation->set_rules('set_code', 'Set name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->data['students'] = $this->super_model->get_members_with_out_group();
$this->data['sets'] = $this->super_model->get_group_list_for_code_invite();
$this->data['content'] = 'root/invitestudent';
$this->load->view('layout/root/template', $this->data);
} else {
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'mail.mydomain.com',
'smtp_port' => 25,
'smtp_user' => 'root',
'smtp_pass' => '347y6Z45Rwlfub020',
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$len = 8;
$type = 'HhJjKkMmNnPpQqRrSsTt';
$set = $this->input->post('set_code');
//$new_password = rand(34546, 89757);
$this->email->from('admin#passwordmanager.com', "Admin Manager");
$this->email->to($this->input->post('student_email'));
//$this->email->cc($this->input->post('student_email'));
$this->email->subject('BSN-Set Code');
//$this->flexi_auth->forgotten_password($identity);
$this->email->message("You are invited to join the group. Your set code is: $set");
$data['message'] = "Sorry Unable to send email...";
if ($this->email->send()) {
$data['message'] = "Mail sent...";
}
redirect('root/administrator/invitesuccess');
}
} else {
$this->data['students'] = $this->super_model->get_members_with_out_group();
$this->data['sets'] = $this->super_model->get_group_list_for_code_invite();
$this->data['content'] = 'root/invitestudent';
$this->load->view('layout/root/template', $this->data);
}
}
Image is here
you can use like this
// Array ( [0] => c#gmail.com [1] => a#gmail.com [2] => b#gamil.com )
$addresses = implode(',',$this->input->post('student_email');
// c#gmail.com,a#gmail.com,b#gamil.com
$this->email->to($addresses);
I have this form I've been playing around with in Wordpress.
It works, but here is the problem...
When the page loads, the contact form is blank (obviously)
If info is not put in text fields, form will not send (obviously)
If info IS put in text fields it will send, "Submit" button will disable and the text on the "Submit" button will change from "Submit Message" to "Submitting, please wait..."
When message has finished sending, a "success message" will pop up over the form for 2.5 seconds, the input fields will be cleared back to a blank form, "Submit" button text reverts back to original "Submit Message" text.
Now, WITHOUT refreshing the page, I want to send a NEW message using the blank form.
I fill in all fields, hit send, and I get an error message saying "Invalid email. You must enter at least one email address." - (the source of this message, I have no idea... I didn't make it, and I have searched high and low through Wordpress files and cannot find where it is coming from)
This error message is referring to the "mail to" email address, which the code pulls from the Wordpress Admin settings.
For some reason, after the form is submitted the first time, it "uses" that mail-to address, and will not allow it to be used again unless the page is reset.
Is there a solution here so that I can send a message... form will automatically clear... I can send a new message, form will automatically clear... I can send a new message... and so on, WITHOUT having to refresh the page after each message submission.
Here is the code:
<?php /* Template Name: Contact Form */ ?>
<?php get_header(); ?>
<div id="top-div"></div>
<div id="container">
<div id="inner-headline">
<h2>
<?php
$headline = get_post_meta($post->ID, "_headline", $single = false);
if(!empty($headline[0]) )
{
echo $headline[0];
}
else
{
the_title();
}
?>
</h2>
</div>
<div id="content">
<div id="content-inner">
<div class="sideright-left-col">
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)): ?>
<p class="error"><?php _e('There was an error submitting the form.',
'Sona')?><p>
<?php endif ?>
<div id="status"></div>
<form action=() id="contact-form" method="post">
<div class="name">
<label for="contactName"><span style="color: red;">* </span>
<?php _e( 'Name', 'Sona' ); ?>:
</label>
<input type="text" name="contactName" id="contactName"
value="<?php if(isset($_POST['contactName'])) echo
$_POST['contactName'];?>" class="requiredField txt"/>
<?php if(isset($nameError) && $nameError != ''): ?><span
class="error"><?php echo $nameError;?></span><?php endif;?>
<div class="clear"></div>
</div>
<div class="email">
<label for="email"><span style="color: red;">* </span>
<?php _e( 'E-mail', 'Sona' ); ?>:
</label>
<input type="text" name="email" id="email"
value="<?php if(isset($_POST['email'])) echo
$_POST['email'];?>" class="requiredField email txt" />
<?php if(isset($emailError) && $emailError != ''): ?><span
class="error"><?php echo $emailError;?></span><?php endif;?>
<div class="clear"></div>
</div>
<div class="subject">
<label for="subject"><span style="color: red;">* </span>
<?php _e( 'Subject', 'Sona' ); ?>:</label>
<input type="text" name="subject" id="subject"
value="<?php if(isset($_POST['subject'])) echo
$_POST['subject'];?>" class="requiredField txt"/>
<?php if(isset($subjectError) && $subjectError != ''): ?><span
class="error"><?php echo $subjectError;?></span><?php endif;?>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="message">
<label for="message"><span style="color: red;">* </span>
<?php _e( 'Message', 'Sona' ); ?>:</label>
<textarea name="message" cols="100" rows="200" id="message"
class="txt requiredField"><?php echo isset($_POST['message']) &&
$_POST['message']!='' ? stripslashes($_POST['message']) : ''?>
</textarea>
<?php if(isset($messageError) && $messageError != '') { ?><span
class="error"><?php echo $messageError;?></span> <?php } ?>
<div class="clear"></div>
</div>
<div>
<?php
$al_options = get_option('al_general_settings');
$options = array(
$al_options['al_contact_error_message'],
$al_options['al_contact_success_message'],
$al_options['al_subject'],
$al_options['al_email_address'],
);
?>
<input type="hidden" name = "options" value="
<?php echo implode(',', $options) ?>" />
<br />
<input type="submit" class="button white-back"
value="Submit Message" tabindex="5" id="submit" name="send"/>
<div class="clear"></div>
</div>
</form>
</div>
<div class="sideright-right-col">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Contact
Sidebar") ) : ?> <?php endif;?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<?php endwhile; ?>
<?php endif; ?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#contact-form").validate({
submitHandler: function() {
var postvalues = jQuery("#contact-form").serialize();
jQuery('#submit').attr('disabled',"disabled");
jQuery('#submit').attr('value', "Submitting, please wait...");
jQuery.ajax
({
type: "POST",
url: "<?php echo get_template_directory_uri() ?>/contact-form.php",
data: postvalues,
success: function(response)
{
jQuery('#status').addClass('success-
message').html(response).show().delay(2500).fadeOut();
jQuery('input:not(#submit)').val("");
jQuery('textarea').val("");
jQuery('#submit').attr('value', "Submit Message");
jQuery('#submit').removeAttr('disabled');
}
});
return false;
},
focusInvalid: true,
focusCleanup: false,
rules:
{
contactName: {required: true},
email: {required: true, minlength: 6,maxlength: 50, email:true},
message: {required: true},
subject: {required: true}
},
messages:
{
contactName: {required: "<?php _e( 'This field is required', 'Sona' ); ?>"},
email: {required: "<?php _e( 'This field is required', 'Sona' ); ?>",
email: "<?php _e( 'Please provide a valid e-mail address.', 'Sona' ); ?>"},
message: {required: "<?php _e( 'This field is required', 'Sona' ); ?>"},
subject: {required: "<?php _e( 'This field is required', 'Sona' ); ?>"}
},
errorPlacement: function(error, element)
{
error.insertAfter(element);
},
invalidHandler: function()
{
jQuery("body").animate({ scrollTop: 0 }, "slow");
}
});
});
</script>
<?php get_footer(); ?>
Try this,
Inside your ajax response section after submitting the form you got success message ,
So just clear current forms like below.
jQuery.ajax
({
type: "POST",
url: "<?php echo get_template_directory_uri() ?>/contact-form.php",
data: postvalues,
success: function(response)
{
jQuery('#status').addClass('success-
message').html(response).show().delay(2500).fadeOut();
// to clear all inputs
//jQuery("#contact-form input").val('');
jQuery("#contact-form input.requiredField").val('');
jQuery('#message').val("");
jQuery('input:not(#submit)').val("");
jQuery('#submit').attr('value', "Submit Message");
jQuery('#submit').removeAttr('disabled');
}
});
Hope its helps..
<?php
$al_options = get_option('al_general_settings');
$options = array(
$al_options['al_contact_error_message'],
$al_options['al_contact_success_message'],
$al_options['al_subject'],
$al_options['al_email_address'],
);
?>
<input type="hidden" name = "options" value="<?php echo implode(',', $options) ?>" />
Add new ID to the input and call it #options
<input id="options" type="hidden" name = "options" value="<?php.....
ADD #options to...
jQuery('input:not(#submit)').val("");
So now it reads...
jQuery('input:not(#submit, #options)').val("");
Bingo!
I'm trying to make an ajax request with jquery/codeigniter. Well, there seems to be a problem. i do get it to work, but it seems like the POST is not sent, for some reason...
Javascript
$('#profileUpdateButton').click(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
From the codeigniter controller
if($this->input->is_ajax_request()) {
echo $this->input->post('profileUpdate');
}
If i replace the "echo $this->" etc.. with just echo "Hello" i do get an alertbox with "Hello", why don't i get the text from the box?
html
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
Change your html markup to this...
<div id="statusUpdate"> <!-- Use ID not NAME here |v| -->
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
you were setting the form's name and you were selecting $('#statusUpdateForm') which means the id of statusUpdateForm, not the name attribute...