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>
Related
view:
<script>
$(function(){
$( "#insert" ).click(function(event)
{
event.preventDefault();
var name= $("#name").val();
var email= $("#email").val();
var phone= $("#phone").val();
var message= $("#message").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url('index.php/'); ?>test/register",
data:{"name": name, "email":email, "phone":phone, "message":message},
success:function(data)
{
console.log(data);
$('#msd').text('Your Enquiry Has Been Sent. We Will Inform You Soon.');
$('#name,#email,#message,#phone').val('');
}
});
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Header</h4>
</div>
<div class="modal-body" id="bg-image">
<div class="row">
<div class="col-md-6">
<form method="post" enctype="multipart/form-data">
<input type="text" class="form-control1" id="name" name="name" placeholder="Enter Your Name" required>
<input type="text" class="form-control1" id="email" name="email" placeholder="Enter Your Email Id" required>
<input type="text" class="form-control1" id="phone" name="phone" placeholder="Enter Your Phone" required>
<textarea class="form-control1" name="message" id="message" placeholder="Enter Your Message" required></textarea>
<input type="submit" name="insert" id="insert" value="Submit">
</form>
</div>
<div class="col-md-6">
<h4>Features</h4>
</div>
</div>
</div>
<div class="modal-footer">
<h4>Fotter</h4>
</div>
</div>
</div>
</div>
controller:
public function register()
{
$register = $this->Fetch_data->contact();
if(!empty($register_user))
{
return true;
}
else
{
return false;
}
}
models:
public function contact()
{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'message' => $this->input->post('message'),
's_date' => date('Y-m-d')
);
$this->db->insert('contact', $data);
}
In this code I have create a form inside the modal where I am inserting form value into database table name contact. Here, form value are inserting successfully but the validation are not working properly. If input field empty they show nothing like field is mandatory. So, How can we give validation to all field please help me ?
Thank You
Try This
Replace <script> To
<script>
$(function(){
$( "#insert").click(function(event)
{
event.preventDefault();
var name= $("#name").val();
var email= $("#email").val();
var phone= $("#phone").val();
var message= $("#message").val();
$.ajax(
{
type:"post",
url: "<?php echo base_url('index.php/'); ?>test/register",
dataType:'JSON',
data:{"name": name, "email":email, "phone":phone, "message":message},
success:function(data)
{
console.log(data);
$('#msd').text(data.message);
}
});
});
});
</script>
Controller
public function register()
{
$this->load->library('form_validation');
$post = $this->input->post();
if (!empty($post)) {
//validate form input
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'E-mail', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('message', 'Message', 'required');
if ($this->form_validation->run() == true) {
$register = $this->Fetch_data->contact($post);
if (!empty($register)) {
echo json_encode(array("status" => false, "message" => "Inserted Successfully"));
exit(0);
} else {
echo json_encode(array("status" => false, "message" => "Unable to insert Try later"));
exit(0);
}
} else {
echo json_encode(array("status" => false, "message" => validation_errors()));
exit(0);
}
} else {
echo json_encode(array("status" => false, "message" => "Invalid Request"));
exit(0);
}
}
Model
public function contact($post)
{
$data = array(
'name' => $post['name'],
'email' => $post['email'],
'phone' => $post['phone'],
'message' => $post['message'],
's_date' => date('Y-m-d', time())
);
$this->db->insert('contact', $data);
return $this->db->insert_id();
}
If You got any error then let me know
Note
Note : Enable Form_validation library
I am currently doing a project and on my project there's an login modal. The things that I've done so far using ajax are: 1) Check the both field username and password have a value; 2) The username field only has a value(password field is blank); 3) Check if the account is verified or not
NOTE: I just tried if($data['validateLogin'] > 0) if it is has a value, yes it is working but when I inputted the correct username and password it still give me an error "Incorrect username or password"
Question: How can check if the username and password is correct? Is my condition wrong? if($data['validateLogin'] > 0)?
Login Modal view
<!-- Login -->
<div id="myLogin" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<form id="login" encrypt="multipart/form-data">
<div class="form-group">
<label> Username: </label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label> Password: </label>
<input type="password" class="form-control" name="password" id="password">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary"> Login </button>
</form>
<a data-toggle="modal" href="#mySignup" data-dismiss="modal">Sign up</a>
</div>
</div>
</div>
</div>
AJAX for my login modal
$("#login").on('submit',function(event){
$.ajax({
url: "http://localhost/itsq/User/validate_user",
type: "POST",
data: $(this).serialize(),
success: function(data) {
var result = JSON.parse(data);
//alert(data);
if(result===1)
{
swal({
type: 'success',
html: 'Update Successful!',
timer: 2000,
})
setTimeout(function() {
document.location.href=base_url + "User/";
}, 2000);
// document.location.href="http://localhost/ecom/Administrator/view_staff_Account";
}
else
{
swal({
type: 'error',
html: result,
timer: 2000,
})
console.clear();
}
// $.LoadingOverlay("hide");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
}
})
event.preventDefault();
});
Controller
public function validate_user()
{
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert" style="padding:2px">', '</div>');
$this->form_validation->set_rules('username', 'Username', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
if ($this->form_validation->run() == FALSE)
{ //if validation is false go to itemList
echo json_encode(validation_errors());
}
else
{
$username = $_POST['username'];
$password = $_POST['password'];
$data['validateLogin'] = $this->CrudModel->validate_user($username,md5($password));
if($data['validateLogin'] > 0) // If there's no match then do this
{
echo json_encode("Incorrect username or password");
}
else // Get all the information for that account
{
foreach($data['validateLogin'] as $vl) // Save it to one variable
{
$user_id = $vl->id;
$status = $vl->status;
}
if($status != "Verified") // Is not verified
{
echo json_encode("Your account is not verified");
}
else
{
$this->session->set_userdata(array('user' => true, 'first_name' => $first_name, 'middle_name' => $middle_name, 'last_name' => $last_name,'gender' => $gender,'age' => $age, 'email' => $email,'username' => $username,'address' => $address, 'credit_card' => $credit_card, 'bank_name' => $bank_name));
redirect('administrator/index',$data);
echo json_encode(1);
}
}
// $this->CrudModel->insert('users', $customer);
// echo json_encode(1);
}
}
Model
// public function validate_user($table,$username_column,$email_column,$password_column,$username, $password)
public function validate_user($table,$username, $password)
{
$this->db->select('username,email,password');
$this->db->where("(email = $username OR username = $username) AND password = $password");
// $query = $this->db->get($table);
$query = $this->db->get();
echo $this->db->last_query();
return $query->result();
// $query = $this->db->get_where($table,array($username_column => $username,$password_column => $password));
// return $query->result();
}
You need to change your condition
if(count($data['validateLogin']) == 0) // If there's no match then do this
If there is a result from validate_user it will return true. If there isn't any results it will return false.
You can check the validity of validate_user result by doing the following. Which will check "If this value is false we will echo error. Else we will continue with login process".
// if NOT true
if(!$data['validateLogin']){
echo json_encode("Incorrect username or password");
}
else {
...
}
I am having a login modal form which is correctly validating but i am having a small problem that it is nt returning false statement on login modal such as Invalid user or password. Whereas in response i see wrong password entered and all html . But no message is printing on form.
here is my view:
Sign In / Order |
<div class="modal fade" id="loginmodel" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content martop105">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title text_center" id="exampleModalLabel">Login</h4>
</div>
<div class="modal-body">
<form >
<div class="row margin0 text_center">
<div class=" col-md-12 col-sm-12 col-xs-12" >
<input type="email" id="email" placeholder="Email*" class="form-control">
</div>
<br>
<div class="col-md-12 col-sm-12 col-xs-12 martop20">
<input type="Password" id="password" placeholder="Password*" class="form-control">
</div>
<br>
<div class="checkbox col-md-12 col-sm-12 col-xs-12 pull-left martop20" >
<label class="pull-left"><input name="remember" type="checkbox" value="Remember Me"> Remember Me</label>
</div>
<div class=" col-md-12 col-sm-12 col-xs-12 pull-left text_blue martop20" >
<a href="#" class="text_blue pull-left">
Forgot password?
</a>
</div>
</div>
<br>
<div class="row margin0 ">
<button type="button" onclick="save();" class="btn btn-info btn-lg marleft20 active">Login</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<script>
function save(){
// alert('ddsfsf');
var email=$('#email').val();
var password=$('#password').val();
// alert(email);
//alert(gender);
$.ajax({
url: '<?php echo base_url();?>Choice/login',
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'text',
success: function(data) {
// console.log(data);
// alert(data);
// alert("Succesfully Saved");
// location.reload(false);
}
});
}
</script>
controller
class Choice extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->database();
$this->load->model('login_model','login_model');
$this->load->library('session');
$this->load->library('eway');
$this->load->model('Catering_model','catering_model');
// $this->load->helper('utility');
$this->load->helper('url');
}
public function login()
{
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[choicelunchuser.email]');
$this->form_validation->set_rules('password','Password','required|callback_basisdata_cek');
if($this->form_validation->run()==false)
{
$this->load->view('ChoiceLaunch/index');
}
else{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['id'];
$data['email'] = $session_data['email'];
$this->load->view('ChoiceLaunch/index',$data);
}
else{
$this->load->view('ChoiceLaunch/index');
}
}
}
public function basisdata_cek()
{
$username= $this->input->post('email');
$password=$this->input->post('password');
// echo $username.' '.$password;
$result=$this->login_model->loginemail($username,$password);
// echo ('fsf'.$result[0]);
// echo ('fsf'.$result[1]);
if($result)
{
$sess_array = array();
foreach ($result as $row)
{
$sess_array = $arrayName = array('id' => $row->id,'email'=> $row->email);
$this->session->set_userdata('logged_in',$sess_array);
// $ci = & get_instance();
//$ci->session->set_userdata("logged_in",$sess_array);
}
return true;
}
else{
//echo $username.' '.$password;
$this->form_validation->set_message('basisdata_cek','Invalid user or password');
return false;
}
}
}
for illustration kindly see pic:
You should add <?php echo validation_errors(); ?> to your view
You can use flash data to print your error message. In your controller
Change
else{
$this->load->view('ChoiceLaunch/index');
}
To
else{
$this->session->set_flashdata('yes', 'Invalid username or password');
redirect('ChoiceLaunch/index');
}
In your login view page add
<?php if($this->session->flashdata('yes')){ ?>
<span style="color:red;"><?php echo $this->session->flashdata('yes'); ?></span>
<?php } ?>
You should load library session.
$this->load->library('session');
Make sure have set base url in config.php
$config['base_url'] = 'http://localhost/projectname/';
dataType to json
function save(){
var email=$('#email').val();
var password=$('#password').val();
$.ajax({
url: "<?php echo base_url('choice/login');?>",
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'json',
success: function(data) {
if ($data['success'] == false) {
// $('#somediv').text($data['error']);
$('#somediv').html($data['error']);
}
if ($data['success'] == true) {
alert('yes')
}
}
});
}
Controller
public function login() {
$data = array();
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[choicelunchuser.email]');
$this->form_validation->set_rules('password','Password','required|callback_basisdata_cek');
if ($this->form_validation->run() == false) {
$data['success'] = false;
$data['error'] = validation_errors();
} else {
// Set the session data
$data['success'] = true;
}
echo json_encode($data);
}
Then You will need to create another ajax function so when click login button to load model will display it.
I have tried to copy from Codegniter's documentation, but I can't make form validation callbacks working.
I added helper form, url and library form_validation. It's not working and always returns "false"
Controller
public function addtest()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($this->form_validation->run() == TRUE)
{
die('true');
}
else
{
die('false');
}
}
$this->template
->build('myform',array());
}
public function username_check($str)
{
if ($str == 'test')
{
return TRUE;
}
else
{
return FALSE;
}
}
View
<form method="post" action="" class="form-horizontal form-label-left">
<div class="col-xs-12 col-md-9">
<div class="x_panel">
<div class="form-group col-xs-12">
<div class="col-xs-3">
<label class="control-label">Folder name</label>
</div>
<div class="col-xs-9">
<input type="text" name="username" value="" class="form-control " id="" placeholder="">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
Extend your form_validation library in Libraries.php
MY_Form_validation.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function run($module = '', $group = '') {
(is_object($module)) AND $this->CI =& $module;
return parent::run($group);
}
}
/* End of file MY_Form_validation.php */
/* Location: ./application/libraries/MY_Form_validation.php */
My Controller function is like this and it runs perfectly. I have autoloaded all libraries
public function change_password()
{
if($this->isLoggedin()){
$data['title']='Change Password';
if($_POST)
{
$config=array(
array(
'field' => 'old_password',
'label' => 'Old Password',
'rules' => 'trim|required|callback_checkPassword'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'conf_password',
'label' => 'Confirm Password',
'rules' => 'trim|required|matches[password]'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == false)
{
// if validation has errors, save those errors in variable and send it to view
$data['errors'] = validation_errors();
$this->load->view('change_password',$data);
}
else
{
// if validation passes, check for user credentials from database
$this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
$this->session->set_flashdata('log_success','Congratulations! Password Changed');
redirect(base_url() . 'Login/dashboard');
}
}
else
{
$this->load->view('change_password',$data);
}
}
else
{
redirect(base_url().'Login');
}
}
public function checkPassword($str)
{
$check=$this->Login_model->checkPassword($str);
if($check)
{
return true;
}
else
{
$this->form_validation->set_message('checkPassword', 'The Current Password you have provided is incorrect');
return false;
}
}
In HTML (Add ID field)
<input type="text" name="username" value="" class="form-control " id="username" placeholder="">
<button type="submit" class="btn btn-success" id="submit">Submit</button>
In your AJAX code
<script type="text/javascript">
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault();
var username= $("#username").username();
$.ajax(
{
type:"post",
url: "<?php echo base_url(); ?>index.php/controller/Method",
data:{ username:username},
success:function(res)
{
}
});
});
});
</script>>
In Controller
No need of check if($_SERVER['REQUEST_METHOD'] == 'POST') because it comes through it always
public function addtest()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
if ($this->form_validation->run() == TRUE)
{
die('true');
}
else
{
die('false');
}
$this->template->build('myform',array());
}
public function username_check($str)
{
if (empty($str))
{
echo "Empty";
}
else
{
if ($str == 'test')
{
return TRUE;
}
else
{
return FALSE;
}
}
}
Check more about CodeIgniter callback function
I have a login popup Modal. and i am logging through ajax
Modal
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
I am trying to redirect after successful login using ajax. If email and password is correct then redirect to any page. If not then it will show the Error.
Controller
function index() {
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
echo validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
echo "Yes";
}else {
echo "No";
}
}
}
This is my controller in which i am checking login user email and password correct/incorrect.
This is my script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(msg) {
if (msg == "Yes")
window.location.href = "<?php echo current_url(); ?>";
else if (msg == "No")
$('#error-msg').html('<div class="alert alert-danger text-center">Incorrect Email & Password. Please try again ...</div>');
else
$('#error-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
});
return false;
});
</script>
As you can see in the success part, when i entered the correct email/password. It is showing Yes. But i want to redirect another page, Why this is showing YES on correct email/password.and On incorrect email/password This is showing NO.
Where i am Doing Wrong???
You need to change few lines of codes in jQuery and Controller function. Here I am attaching updated version of your code. Please refer below:
View (Bootstrap Modal)
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
This is your view file. It will remain same. On clicking on button you have written a script which need to be modified. Will attact after attaching controller's function:
Controller
function index() {
if (!$this->input->is_ajax_request()) {
echo 'No direct script is allowed';
die;
}
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
$result['status'] = 'error';
$result['message'] = validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
$result['status'] = 'success';
$result['message'] = 'Yeah! You have successfully logged in.';
$result['redirect_url'] = base_url();
}else {
$result['status'] = 'error';
$result['message'] = 'Whoops! Incorrect Email & Password. Please try again';
}
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($result));
$string = $this->output->get_output();
echo $string;
exit();
}
Script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(resp) {
if (resp.status == "success")
window.location.href = resp.redirect_url;
else
$('#error-msg').html('<div class="alert alert-danger">' + resp.message + '</div>');
}
});
return false;
});
This is the correct answer. Let me know if you face any issue.
You can use a simple redirect() (comes in the url helper) in your code if you want to jump to another controller/method from the script. However, this will not alert the user that the login was successful: it's just a plain redirect.
The proper way to do it would be returning a json file, so instead of echoing a yes or no, use this:
$response['type'] = 'error';
$response['msg'] = 'Login Succesful';
$response['redirect'] = 'http://your-url.com/controller/method';
echo json_encode($response);
die;
Then, you handle the answer in your ajax call, and some good alerting (in my case, Sweet Alert) kinda like this:
success: function(data) {
if (data.redirect) {
swal({
title: '¡Success!',
text: data.msg,
timer: 2000,
type: data.type,
showConfirmButton: false
}, function() {
window.location.href = data.redirect;
});
} else {
swal('¡Error!', data.msg, data.type);
}
}
So what this code does is that if your json response has a redirect field, will trigger the redirection after a while. But if your json response does not have the field redirect, will just show an alert.
Check your return data type. May be you can use in datatype in Ajax code. Return data can't read if condition. I am facing same problem or use this
if($.trim(msg) == 'Yes') {
Change echo "Yes"; to die("Yes");. This will make sure nothing will be sent after "Yes" or "No" and then the JS code will work as expected.
Their is also a way to redirect from your controller after success.
In this case you just need to follow these two steps to redirect
This line in your controller where you get true condition and want to redirect
if($result){
echo base_url()."welcome/";
}
else{
echo 0;
}
on your html page where you applied your ajax, on true condition you try this to redirect page
success: function(result){
if(result!=0){
// On success redirect.
window.location.replace(result);
}
else
alert('wrong');
}