This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I am trying to make a registration where website sends a confirmation email and users enter this email and continue registering. However, it doesn't send anything to email. Where am I wrong?
Here is my controller.php:
<?php
class user extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url', 'security'));
$this->load->library(array('session', 'form_validation', 'email'));
$this->load->database();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
//set validation rules
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean');
$this->form_validation->set_rules('mail', 'Email', 'trim|required|valid_email|is_unique[instructors.mail]');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|md5|matches[password]');
$data['courses'] = $this->Popular_courses_model->get_popular_courses();
$data['news'] = $this->News_model->get_news();
//validate form input
if ($this->form_validation->run() == FALSE)
{
// fails
$this->load->view('templates/header');
$this->load->view('pages/index', $data);
$this->load->view('templates/footer');
}
else
{
//insert the user registration details into database
$data = array(
'instructors_slug' => $this->input->post('username'),
'mail' => $this->input->post('mail'),
'password' => $this->input->post('password')
);
// insert form data into database
if ($this->User_model->insertUser($data))
{
// send email
if ($this->User_model->sendEmail($this->input->post('mail')))
{
// successfully sent mail
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect('user/register');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user/register');
}
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user/register');
}
}
}
function verify($hash=NULL)
{
if ($this->User_model->verifyEmailID($hash))
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
redirect('user/register');
}
else
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
redirect('user/register');
}
}
}
?>
Here is my model:
<?php
class user_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//insert into user table
function insertUser($data)
{
return $this->db->insert('instructors', $data);
}
//send verification email to user's email id
function sendEmail($to_email)
{
$from_email = 'support#wtf.az'; //change this to yours
$subject = 'Verify Your Email Address';
$message = 'Dear User,<br /><br />Please click on the below activation link to verify your email address.<br /><br /> http://wtf.az/user/verify/' . md5($to_email) . '<br /><br /><br />Thanks<br />Mydomain Team';
//configure email settings
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'cpanel.freehosting.com'; //smtp host name
$config['smtp_port'] = '465'; //smtp port number
$config['smtp_user'] = $from_email;
$config['smtp_pass'] = '*my password here*'; //$from_email password
$config['mailtype'] = 'html';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n"; //use double quotes
$this->email->initialize($config);
//send mail
$this->email->from($from_email, 'WTF');
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
return $this->email->send();
}
//activate user account
function verifyEmailID($key)
{
$data = array('status' => 1);
$this->db->where('md5(mail)', $key);
return $this->db->update('instructors', $data);
}
}
?>
Here is my view:
<div class="modal-body">
<div>
<?php echo $this->session->flashdata('msg'); ?>
</div>
<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
<span class="text-danger"><?php echo form_error('username'); ?></span>
<input name="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('mail'); ?></span>
<input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('password'); ?></span>
<input name="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
<input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon">
<span class="rex-btn-text">регистрация</span>
<span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
</button>
</div>
</form>
</div>
Not sure if this is the issue, but as per the documentation, the model class name must start with a capital letter.
In your model, try changing this:
class user_model extends CI_Model
to this:
class User_model extends CI_Model
Related
I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.
I have added a registration and login system to this application. I am current working on a password reset system.
I can't figure out why updating a user's password fails as below:
In the Newpassword controller I have:
class Newpassword extends CI_Controller {
private $token = NULL;
public function index($token = NULL) {
//echo $token; die();
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'New password';
$data['categories'] = $this->Categories_model->get_categories();
$this->token = $token;
// Form validation rules
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if(!$this->form_validation->run()) {
$this->load->view('partials/header', $data);
$this->load->view('auth/newpassword');
$this->load->view('partials/footer');
} else {
$this->add();
}
}
public function add() {
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'New password';
$data['categories'] = $this->Categories_model->get_categories();
// Encrypt new password
$enc_password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
// Update password column
$token = $this->token;
if ($this->Usermodel->set_new_password($token, $enc_password)) {
redirect('login');
$this->session->set_flashdata("new_password_success", "Your new password was set. You can login");
} else {
$this->session->set_flashdata("new_password_fail", "We have failed updating your password");
redirect('/newpassword');
}
}
}
In the Usermodel model I have:
public function set_new_password($token, $enc_password) {
$this->db
->where(['token' => $token])
// set new password and reset token to NULL
->update('authors', array('password' => $enc_password, 'token' => NULL));
}
The form:
<?php echo form_open(base_url('newpassword/add')); ?>
<div class="form-group <?php if(form_error('password')) echo 'has-error';?>">
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<?php if(form_error('password')) echo form_error('password'); ?>
</div>
<div class="form-group <?php if(form_error('cpassword')) echo 'has-error';?>">
<input type="password" name="cpassword" id="cpassword" class="form-control" placeholder="Confirm password">
<?php if(form_error('cpassword')) echo form_error('cpassword'); ?>
</div>
<div class="form-group mb-2">
<input type="submit" value="Set password" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
If I uncomment //echo $token; die(); from the controller, the token is printed with the expected value. Yet, the password does not update (and the failure to update it is correctly displayed).
What am I doing wrong?
When you click Set password button redirected to newpassword/add but the token not exists here, because used it only a previous step:
Password reset request
Click link in email (token exist)
Fill the form and click "Set password" (send form data to newpassword/add) - the token is not exist here but you want to use it: $token = $this->token; but now the "token" is: add
Sorry, you must be refactoring your password reset code logic. I think this is harder to fix than rewriting the whole process
UPDATE:
Add $data['token'] = $token; into index method in Newpassword controller
AND
modify form action url in views/auth/newpassword.php to this:
<?php echo form_open(base_url('newpassword/add/'.$token)); ?>
IMPORTANT!!!
Add return to ell functions in model:
return $this->db-> ....
And put redirect('<url>') after set session flashdata!
I tested it and I think fixed the problem.
This is the final, working code for the password update (in case anybody else needs it):
In the Newpassword controller:
class Newpassword extends CI_Controller
{
public function index($token = NULL)
{
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'New password';
$data['categories'] = $this->Categories_model->get_categories();
$data['token'] = $token;
// Form validation rules
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if (!$this->form_validation->run()) {
$this->load->view('partials/header', $data);
$this->load->view('auth/newpassword');
$this->load->view('partials/footer');
} else {
// Encrypt new password
$enc_password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
if ($this->Usermodel->set_new_password($token, $enc_password)) {
$this->session->set_flashdata("new_password_success", "Your new password was set. You can login");
redirect('login');
} else {
$this->session->set_flashdata("new_password_fail", "We have failed updating your password");
redirect('/newpassword/' . $token);
}
}
}
}
In the model:
public function set_new_password($token, $enc_password) {
return $this->db
->where('token', $token)
// set new password and reset token to NULL
->update('authors', array('password' => $enc_password, 'token' => NULL));
}
The form (view):
<?php echo form_open(base_url('newpassword/'. $token)); ?>
<div class="form-group <?php if(form_error('password')) echo 'has-error';?>">
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<?php if(form_error('password')) echo form_error('password'); ?>
</div>
<div class="form-group <?php if(form_error('cpassword')) echo 'has-error';?>">
<input type="password" name="cpassword" id="cpassword" class="form-control" placeholder="Confirm password">
<?php if(form_error('cpassword')) echo form_error('cpassword'); ?>
</div>
<div class="form-group mb-2">
<input type="submit" value="Set password" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
I have a user system with user registration and user login. on the login page there is a password reset button and on the password rest button the following codes are there but nothing happens when I try to send a password rest link.
CONTROLLER:
function resetPasswordUser()
{
$status = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('login_email','Email','trim|required|valid_email|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->forgotPassword();
}
else
{
$email = $this->input->post('login_email');
if($this->user_model->checkEmailExist($email))
{
$encoded_email = urlencode($email);
$this->load->helper('string');
$data['email'] = $email;
$data['activation_id'] = random_string('alnum',15);
$data['createdDtm'] = date('Y-m-d H:i:s');
$data['agent'] = getBrowserAgent();
$data['client_ip'] = $this->input->ip_address();
$save = $this->user_model->resetPasswordUser($data);
if($save)
{
$data1['reset_link'] = base_url() . "resetPasswordConfirmUser/" . $data['activation_id'] . "/" . $encoded_email;
$userInfo = $this->user_model->getCustomerInfoByEmail($email);
if(!empty($userInfo)){
$data1["username"] = $userInfo[0]->username;
$data1["email"] = $userInfo[0]->email;
$data1["message"] = "Reset Your Password";
}
$sendStatus = resetPasswordEmail($data1);
if($sendStatus){
$status = "send";
setFlashData($status, "Reset password link sent successfully, please check mails.");
} else {
$status = "notsend";
setFlashData($status, "Email has failed, try again.");
}
}
else
{
$status = 'unable';
setFlashData($status, "It seems an error while sending your details, try again.");
}
}
else
{
$status = 'invalid';
setFlashData($status, "This email is not registered with us.");
}
redirect('users/forgotPassword');
}
}
// This function used to reset the password
function resetPasswordConfirmUser($activation_id, $email)
{
// Get email and activation code from URL values at index 3-4
$email = urldecode($email);
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
$data['email'] = $email;
$data['activation_code'] = $activation_id;
if ($is_correct == 1)
{
$this->load->view('templates/header');
$this->load->view('newPassword', $data);
$this->load->view('templates/footer');
}
else
{
redirect('users/login');
}
}
// This function used to create new password
function createPasswordUser()
{
$status = '';
$message = '';
$email = $this->input->post("email");
$activation_id = $this->input->post("activation_code");
$this->load->library('form_validation');
$this->form_validation->set_rules('password','Password','required|max_length[20]');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]|max_length[20]');
if($this->form_validation->run() == FALSE)
{
$this->resetPasswordConfirmUser($activation_id, urlencode($email));
}
else
{
$password = $this->input->post('password');
$cpassword = $this->input->post('cpassword');
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
if($is_correct == 1)
{
$this->user_model->createPasswordUser($email, $password);
$status = 'success';
$message = 'Password changed successfully';
}
else
{
$status = 'error';
$message = 'Password changed failed';
}
setFlashData($status, $message);
redirect("users/login");
}
}
MODEL:
function checkEmailExist($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return true;
} else {
return false;
}
}
/**
* This function used to insert reset password data
* #param {array} $data : This is reset password data
* #return {boolean} $result : TRUE/FALSE
*/
function resetPasswordUser($data)
{
$result = $this->db->insert('reset_password', $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
/**
* This function is used to get customer information by email-id for forget password email
* #param string $email : Email id of customer
* #return object $result : Information of customer
*/
function getCustomerInfoByEmail($email)
{
$this->db->select('id, email, username');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('email', $email);
$query = $this->db->get();
return $query->result();
}
/**
* This function used to check correct activation deatails for forget password.
* #param string $email : Email id of user
* #param string $activation_id : This is activation string
*/
function checkActivationDetails($email, $activation_id)
{
$this->db->select('id');
$this->db->from('reset_password');
$this->db->where('email', $email);
$this->db->where('activation_id', $activation_id);
$query = $this->db->get();
return $query->num_rows;
}
// This function used to create new password by reset link
function createPasswordUser($email, $password)
{
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$this->db->update('users', array('password'=>getHashedPassword($password)));
$this->db->delete('reset_password', array('email'=>$email));
}
VIEW:
<div class="row">
<div class="col-md-12">
<?php echo validation_errors('<div class="alert alert-danger alert-dismissable">', ' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>'); ?>
</div>
</div>
<?php
$this->load->helper('form');
$error = $this->session->flashdata('error');
$send = $this->session->flashdata('send');
$notsend = $this->session->flashdata('notsend');
$unable = $this->session->flashdata('unable');
$invalid = $this->session->flashdata('invalid');
if($error)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php }
if($send)
{
?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $send; ?>
</div>
<?php }
if($notsend)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $notsend; ?>
</div>
<?php }
if($unable)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $unable; ?>
</div>
<?php }
if($invalid)
{
?>
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $invalid; ?>
</div>
<?php } ?>
<form action="<?php echo base_url(); ?>users/resetPasswordUser" method="post">
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" name="login_email" required />
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div><!-- /.col -->
<div class="col-xs-4">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="Submit" />
</div><!-- /.col -->
</div>
</form>
Login<br>
</div><!-- /.login-box-body -->
</div><!-- /.login-box -->
CONSTANT:
define('EMAIL_FROM', 'xxxx#gmail.com'); // e.g. email#example.com
define('EMAIL_BCC', 'xxxx#gmail.com'); // e.g. email#example.com
define('FROM_NAME', 'CTL '); // Your system name
define('EMAIL_PASS', 'Your email password'); // Your email password
define('PROTOCOL', 'smtp'); // mail, sendmail, smtp
define('SMTP_HOST', 'smtp.gmail.com'); // your smtp host e.g. smtp.gmail.com
define('SMTP_PORT', '25'); // your smtp port e.g. 25, 587
define('SMTP_USER', 'Your smtp user'); // your smtp user
define('SMTP_PASS', 'Your smtp password'); // your smtp password
define('MAIL_PATH', '/usr/sbin/sendmail');
QUESTION UPDATE
I changed my view to load out my errors and what I get is "Email has failed, try again." Error for mail not sent. Thanks
From your comments, it looks like you are using a localhost server. Localhost servers cannot send emails out IIRC. To test sending emails, you have to have a server that has access to the real world (and the feature has to be enabled on that server).
I want to make registration in CodeIgniter. Everything is fine, however, I want to add Ajax to show error and success messages. However, it does not work. Here is my view:
<div class="modal-body">
<div id="messages"></div>
<?php $attributes = array('class' => 'rex-forms', 'name' => 'registrationform', 'id' => 'registrationform'); ?>
<?= form_open_multipart('user/register', $attributes); ?>
<div class="form-group">
<span class="text-danger"><?php echo form_error('username'); ?></span>
<input name="username" type="text" class="form-control" placeholder="Имя пользователя">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('mail'); ?></span>
<input name="mail" type="email" class="form-control" placeholder="Электронный адрес">
</div>
<div class="form-group">
<span class="text-danger"><?php echo form_error('password2'); ?></span>
<input name="password" type="password" class="form-control" placeholder="Пароль">
</div>
<div class="form-group">
<input name="password2" type="password" class="form-control" placeholder="Повторный ввод пароля">
</div>
</div>
<div class="modal-footer">
<button type="submit" name="submitforreg" class="rex-bottom-medium rex-btn-icon">
<span class="rex-btn-text">регистрация</span>
<span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
</button>
</div>
</form>
</div>
Here is my controller:
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url', 'security'));
$this->load->library(array('session', 'form_validation', 'email'));
$this->load->database();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
//set validation rules
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]|is_unique[instructors.instructors_slug]xss_clean');
$this->form_validation->set_rules('mail', 'Email', 'trim|required|valid_email|is_unique[instructors.mail]');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');
$this->form_validation->set_rules('password2', 'Confirm Password', 'trim|required|md5|matches[password]');
$to_email= $this->input->post('mail');
$data['courses'] = $this->popular_courses_model->get_popular_courses();
$data['news'] = $this->news_model->get_news();
//validate form input
if ($this->form_validation->run() == FALSE)
{
// fails
$this->load->view('templates/header');
$this->load->view('pages/index', $data);
$this->load->view('templates/footer');
}
else
{
//insert the user registration details into database
$data = array(
'instructors_slug' => $this->input->post('username'),
'mail' => $to_email,
'password' => $this->input->post('password')
);
// insert form data into database
if ($this->user_model->insertUser($data)) {
if ($this->user_model->sendEmail($to_email)) {
// successfully sent mail
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect('user/register');
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.$to_email.' gondermir '.$this->email->print_debugger().'</div>');
redirect('user/register');
}
}
else
{
// error
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">daxil elemir</div>');
redirect('user/register');
}
}
}
public function login(){
$data['title'] = 'Sign In';
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_dash|min_length[3]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|md5|min_length[3]');
if($this->form_validation->run() === FALSE){
$this->load->view('login/login', $data);
} else {
// Get username
$username = $this->input->post('username');
// Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'instructor_id' => $instructor_id,
'id' => $id,
'instructors_slug' => $username,
'name' => $name,
'logged_in' => true
);
$this->session->set_userdata($user_data);
redirect('');
} else {
$this->session->set_flashdata('login_failed', 'Неверныый логин или пароль');
redirect('');
}
}
}
public function logout() {
$this->session->unset_userdata('logged_in');
$this->session->unset_userdata('instructor_id');
$this->session->unset_userdata('id');
$this->session->unset_userdata('instructors_slug');
$this->session->unset_userdata('name');
redirect('');
}
function verify($hash=NULL)
{
if ($this->user_model->verifyEmailID($hash))
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
redirect('');
}
else
{
$this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
redirect('');
}
}
}
?>
and here is my register.js file:
$(document).ready(function() {
$("#registrationform").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
response.messages+
'</div>');
$("#registerForm")[0].reset();
$(".text-danger").remove();
$(".form-group").removeClass('has-error').removeClass('has-success');
}
else {
$.each(response.messages, function(index, value) {
var element = $("#"+index);
$(element)
.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
$(element).after(value);
});
}
} // /success
}); // /ajax
return false;
});
});
You problem is the dynamic binding issue.
Maybe you are calling the ready function before the JQuery Javascript is included?
Here is your error.
Uncaught ReferenceError: $ is not defined at register.js:
// Remove This.
//$(document).ready(function() {
//$("#registrationform").unbind('submit').bind('submit', function() {
// var form = $(this);
// Add This.
$('#your_model_id').on('click', '.submit_button_class', function(e) {
var str = $( "#registrationform" ).serialize();
And Please You should put the references to the jquery scripts first.
like this.
<script language="JavaScript" type="text/javascript" src="your_script.js"></script>
I am trying to make a simple page where users will request for some services they would like to have. After passing the validation I save the form data into a database. This program should also send an email notification when someone ask for some services. So, Until this my code is working.
But I want to get the form data in the email body/message when a form is successfully submited but so far I could not manage to do it. I googled and tried some but did not work.
How can I do it using codeigniter? Could someone guide me how can I fix this? If you need full HTML code please let me know. I would appreciate your help.
Contact.php file (Controller)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Contact extends CI_Controller {
function __construct()
{
parent::__construct();
//load the contact_model
$this->load->model('contact_model');
}
public function index()
{
//load view pages
$this->load->view('Template/header');
$this->load->view('contact');
$this->load->view('Template/footer');
}
public function validate_form()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//FORM VALIDATION
//First Name
$this->form_validation->set_rules('first_name', 'First Name', 'trim|required|min_length[3]|max_length[17]');
//Last Name
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|min_length[3]|max_length[17]');
//User Name
$this->form_validation->set_rules('user_name', 'User Name', 'trim|required|alpha|strtolower|min_length[3]');
//Email
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
//Manager's Full Name
$this->form_validation->set_rules('m_name', 'Full Name', 'trim|required');
//Comment
$this->form_validation->set_rules('comment', 'Comment', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
//echo validation_errors();
$this->load->view('Template/header');
$this->load->view('contact');
$this->load->view('Template/footer');
//$redirect = $this->input->post('url');
//$this->session->set_flashdata('errors',validation_errors());
}
else
{
$specialised_category = $this->input->post('checkbox_cat');
$data = array(
'f_name' => $this->input->post('first_name'),
'l_name' => $this->input->post('last_name'),
'user_name' => $this->input->post('user_name'),
'email' => $this->input->post('email'),
'fullname' => $this->input->post('m_name'),
'comment' => $this->input->post('comment'),
'city' => $this->input->post('city'),
//encoding to JSON and comma sepated values
'services_list' => json_encode(implode(",", $specialised_category))
);
//inserting data
//$this->db->insert('sysops_tbl', $data);
$this->contact_model->insert_into_db($data);
//load the form success message once submitted correctly
$this->load->view('formsuccess');
$this->send($data);
//redirect to the main page
//redirect(base_url());
}
}
public function send($value='')
{
//load the email library
$this->load->library('email');
//Sending email
$config_email = array(
'mailtype' => 'html',
'charset' =>'iso-8859-1',
'wordwrap' => TRUE
);
//debug
//print_r($value);
//override the config from text to html
$this->email->initialize($config_email);
//printing manager email and name
$this->email->from($this->input->post('email'),$this->input->post('m_name'));
//receipant email
$this->email->to('xxx.xx#xxx.com');
//header
//$this->email->set_header(json_encode(implode(",", $this->input->post('checkbox_cat'))),'binded');
//email subject
$this->email->subject('We need user access for');
//want to inject values here in the email message
$this->email->message('Check above !!:');
//print the message if email is sent
if($this->email->send())
{
return TRUE;
//echo "Email is sent";
}else
{
return FALSE;
//echo $this->email->print_debugger();
}
}
}
?>
for check boxes partial code is given
contact.php (views)
<div class="form-group">
<label class="col-md-4 control-label">Which ?</label>
<div class="col-md-4">
<div class="checkbox">
<label>
<input type="checkbox" name="checkbox_cat[]" class="get_value" value="option4" /> option4
</label>
<label>
<input type="checkbox" name="checkbox_cat[]" class="get_value" value="option5" /> option5
</label>
<label>
<input type="checkbox" name="checkbox_cat[]" class="get_value" value="option6" /> option6
</label>
<label>
<input type="checkbox" name="checkbox_cat[]" class="get_value" value="option7" /> option7
</label>
</div>
</div>
contact_model.php (model)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class contact_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function insert_into_db($data)
{
// Inserting into database table
$this->db->insert('sysops_tbl', $data);
}
}
?>
public function send($value='')
{
//load the email library
$this->load->library('email');
//Sending email
$config_email = array(
'mailtype' => 'html',
'charset' =>'iso-8859-1',
'wordwrap' => TRUE
);
$msg = $this->load->view('email_template',$value,true);
//override the config from text to html
$this->email->initialize($config_email);
//printing manager email and name
$this->email->from($this->input->post('email'),$this->input->post('m_name'));
//receipant email
$this->email->to('xxx.xx#xxx.com');
//header
//$this->email->set_header(json_encode(implode(",", $this->input->post('checkbox_cat'))),'binded');
//email subject
$this->email->subject('We need user access for');
$this->email->message($msg);
//print the message if email is sent
if($this->email->send())
{
return TRUE;
//echo "Email is sent";
}else
{
return FALSE;
//echo $this->email->print_debugger();
}
}
email_template : Design it as you required
<html>
<div>
<label>Name</label>
<?php echo $f_name." ".$l_name; ?>
</div>
<div>
<label>Comment</label>
<?php echo $comment; ?>
</div>
</html>
I am newbie at CodeIgniter. I am trying to implement form validation in user registration.
$autoload['libraries'] = array('database','session','encrypt','form_validation');
$autoload['helper'] = array('url','file','form');
$autoload['model'] = array('user_model');
Controller's Code:
class User_registration extends CI_Controller {
public function index() {
$this->register();
}
function register() {
//set validation rules
$this->load->library('form_validation');
$this->form_validation->set_rules('user_name', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
$this->form_validation->set_rules('email_id', 'Email ID', 'trim|required|valid_email|is_unique[email_id]');
$this->form_validation->set_rules('user_password', 'Password', 'trim|required|matches[confirm_password]|md5');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|md5');
//validate form input
if ($this->form_validation->run() == FALSE) {
// fails
$data = array();
$data['title'] = 'Registration | Admin Panel';
$data['header_content'] = $this->load->view('adminEntry/header_content', '', true);
$data['footer_content'] = $this->load->view('adminEntry/footer_content', '', true);
$this->load->view('adminentry/user_registration', $data);
} else {
//insert the user registration details into database
echo '<pre>';
print_r($data);
exit();
$data = array(
'user_name' => $this->input->post('user_name'),
'email_id' => $this->input->post('email_id'),
'password' => $this->input->post('user_password'),
);
if ($this->user_model->insertuser($data)) {
if ($this->user_model->sendEmail($this->input->post('email_id'))) {
// successfully sent mail
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
redirect('user_registration');
} else {
// error
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user_registration');
}
} else {
// error
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('user_registration');
}
}
}
User Model:
class User_model extends CI_Model {
//insert into user table
function insertUser($data) {
return $this->db->insert('user', $data);
}
function sendEmail($to_email) {
$from_email = 'sample#mail.com'; //change this to yours
$subject = 'Verify Your Email Address';
$message = 'Dear User,<br /><br />Please click on the below activation link to verify your email address.<br /><br /> http://example.com/user/verify/' . md5($to_email) . '<br /><br /><br />Thanks<br />Mydomain Team';
//configure email settings
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.example.com'; //smtp host name
$config['smtp_port'] = '465'; //smtp port number
$config['smtp_user'] = $from_email;
$config['smtp_pass'] = 'examplepass'; //$from_email password
$config['mailtype'] = 'html';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n"; //use double quotes
$this->email->initialize($config);
//send mail
$this->email->from($from_email, 'example.com');
$this->email->to($to_email);
$this->email->subject($subject);
$this->email->message($message);
return $this->email->send();
}
//activate user account
function verifyEmailID($key) {
$data = array('approval_status' => 1);
$this->db->where('md5(email_id)', $key);
return $this->db->update('user', $data);
}
}
View Page:
<div class="container">
<div class="full-content-center animated fadeInDownBig">
<p class="text-center"><img src="<?php echo base_url(); ?>adminAssets/img/login-logo.png" alt="Logo"></p>
<div class="login-wrap">
<div class="row">
<div class="col-sm-6">
<?php echo $this->session->flashdata('verify_msg'); ?>
</div>
</div>
</div>
<div class="login-block">
<?php
$attributes = array("name" => "registrationform");
echo form_open("user_registration/index", $attributes);
?>
<form role="form" method="post" action="<?php echo base_url(); ?>user_registration" enctype="multipart/form-data>">
<div class="form-group login-input">
<i class="fa fa-user overlay"></i>
<input type="text" name="user_name" value="<?php echo set_value('user_name'); ?>" class="form-control text-input" placeholder="Name">
<span class="text-danger"><?php echo form_error('user_name'); ?></span>
</div>
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" name="email_id" value="<?php echo set_value('email_id'); ?>" class="form-control text-input" placeholder="E-mail">
<span class="text-danger"><?php echo form_error('email_id'); ?></span>
</div>
<div class="form-group login-input">
<i class="fa fa-key overlay"></i>
<input type="password" name="user_password" value="<?php echo set_value('user_password'); ?>" class="form-control text-input" placeholder="Password" id="txtNewPassword">
<span class="text-danger"><?php echo form_error('user_password'); ?></span>
</div>
<div class="form-group login-input">
<i class="fa fa-key overlay"></i>
<input type="password" name="confirm_password" value="<?php echo set_value('confirm_password'); ?>" class="form-control text-input" placeholder="Confirm Password" id="txtConfirmPassword" onChange="isPasswordMatch();" >
</div>
<div class="form-group login-input" id="divCheckPassword"></div>
<div class="row">
<div class="col-sm-12">
<button type="submit" name="submit" class="btn btn-default btn-block">Register</button>
</div>
</div>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
</form>
</div>
</div>
</div>
</div>
Here is my error:
Error Number: 1146
Table 'counterpressing.email_id' doesn't exist
SELECT * FROM email_id WHERE email_id = 'shakil#gmail.com' LIMIT 1
Filename: D:/Xampp/htdocs/ffbdhub.com/system/database/DB_driver.php
Line Number: 691
Not sure if this has been brought up, but your validation rule isn't quite right... Your "is_unique()" requires the
table and field, so you have the field name which is email_id, but your table name is nowhere to be seen.
So whatever your table name is for your table containing email_id that you are wanting to check against, you need to change this...
$this->form_validation->set_rules('email_id', 'Email ID', 'trim|required|valid_email|is_unique[email_id]');
To this
$this->form_validation->set_rules('email_id', 'Email ID', 'trim|required|valid_email|is_unique[table_name.email_id]');
In simpler terms, you need to have is_unique[table_name.email_id] , where table_name is the name of the table that contains the email_id you are testing for.
I think you have to load database. Like this
$this->load->database() in file.
This might be solve your problem.