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 {
...
}
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 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 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 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');
}
I'm new to CodeIgniter and need some help :).
I managed to build a CRUD functions with ajax over some tutorials and I can Edit, Add new, Delete all user shown on my page. What I want now is when i Login with a user I just want the Logged in Profile to be Edited, not others. Please if someone can help me how can I manage to do that. Thank You in Advance.
Employee.php Controller
<?php
defined('BASEPATH') OR exit('No direct sripct access allowed');
Class Employee extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Employee_m', 'm');
}
function index()
{
$this->load->view('employee/index');
}
public function showAllEmployee()
{
$result = $this->m->showAllEmployee();
echo json_encode($result);
}
public function add_user()
{
$result = $this->m->add_user();
$msg['success'] = false;
$msg['type'] = 'add';
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
public function edit_user()
{
$result = $this->m->edit_user();
echo json_encode($result);
}
public function update_user()
{
$result = $this->m->update_user();
$msg['success'] = false;
$msg['type'] = 'update';
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
public function delete_user()
{
$result = $this->m->delete_user();
$msg['success'] = false;
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
Employee_m Model
<?php defined('BASEPATH') OR exit('No direct sripct access allowed');
class Employee_m extends CI_Model
{
public function showAllEmployee()
{
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return $query->result();
}
else
{
return false;
}
}
public function add_user()
{
$field = array(
'firstname' => $this->input->post('txtFirstName'),
'lastname' => $this->input->post('txtLastName'),
'username' => $this->input->post('txtUsername'),
'user_email' => $this->input->post('txtUserEmail'),
'user_password' => $this->input->post('txtUserPassword')
);
$this->db->insert('users',$field);
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function get_id(){
$id = $this->input->get('id');
$this->db->where('id',$id);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return $query->result();
}
else
{
return false;
}
}
public function update_user()
{
$id = $this->input->post('txtId');
$field = array(
'firstname' => $this->input->post('txtFirstName'),
'lastname' => $this->input->post('txtLastName'),
'username' => $this->input->post('txtUsername'),
'user_email' => $this->input->post('txtUserEmail'),
'user_password' => $this->input->post('txtUserPassword')
);
$this->db->where('id',$id);
$this->db->update('users',$field);
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
function delete_user()
{
$id = $this->input->get('id');
$this->db->where('id',$id);
$this->db->delete('users');
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
}
Index View
<?php $this->load->view('components/page_head'); ?>
<?php
if (isset($this->session->userdata['logged_in'])) {
$username = ($this->session->userdata['logged_in']['username']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: user_authentication");
}
?>
<div class="col-sm-9">
<div class="alert alert-success" style="display: none;">
</div>
<button id="btnAdd" class="btn btn-success">Add New</button>
<table class="table table-bordered table-responsive" style="margin-top: 20px;">
<thead>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Username</td>
<td>e-Mail</td>
<td>Actions</td>
</tr>
</thead>
<tbody id="showdata">
</tbody>
</table>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<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">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal">
<input type="hidden" name="txtId" value="0">
<div class="form-group">
<label class="label-control col-md-4">First Name</label>
<div class="col-md-6">
<input type="text" name="txtFirstName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Last Name</label>
<div class="col-md-6">
<input type="text" name="txtLastName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Username</label>
<div class="col-md-6">
<input type="text" name="txtUsername" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">e-Mail</label>
<div class="col-md-6">
<input type="email" name="txtUserEmail" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Password</label>
<div class="col-md-6">
<input type="password" name="txtUserPassword" class="form-control" placeholder="******">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<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">Confirm Delete</h4>
</div>
<div class="modal-body">
Do you want to delete this record?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnDelete" class="btn btn-danger">Delete</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
$(function () {
showAllEmployee();
// Add New
$('#btnAdd').click(function () {
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Add new user');
$('#myForm').attr('action','<?php echo base_url() ?>employee/add_user');
});
$('#btnSave').click(function () {
// alert('test');
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// validate the form
var firstname = $('input[name=txtFirstName]');
var lastname = $('input[name=txtLastName]');
var username = $('input[name=txtUsername]');
var user_email = $('input[name=txtUserEmail]');
var user_password = $('input[name=txtUserPassword]');
var result = '';
if (firstname.val()==''){
firstname.parent().parent().addClass('has-error');
}else {
firstname.parent().parent().removeClass('has-error');
result +='1';
}
if (lastname.val()==''){
lastname.parent().parent().addClass('has-error');
}else {
lastname.parent().parent().removeClass('has-error');
result +='2';
}
if (username.val()==''){
username.parent().parent().addClass('has-error');
}else {
username.parent().parent().removeClass('has-error');
result +='3';
}
if (user_email.val()==''){
user_email.parent().parent().addClass('has-error');
}else {
user_email.parent().parent().removeClass('has-error');
result +='4';
}
if (user_password.val()==''){
user_password.parent().parent().addClass('has-error');
}else {
user_password.parent().parent().removeClass('has-error');
result +='5';
}
if(result == '12345'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function (response) {
if (response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('User '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function () {
alert('Could not add Data ');
}
});
}
});
//edit
$('#showdata').on('click', '.item-edit', function() {
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('edit user');
$('#myForm').attr('action','<?php echo base_url() ?>employee/update_user');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>employee/edit_user',
data: {id: id},
async: false,
dataType: 'json',
success: function(data) {
$('input[name=txtFirstName]').val(data.firstname);
$('input[name=txtLastName]').val(data.lastname);
$('input[name=txtUsername]').val(data.username);
$('input[name=txtUserEmail]').val(data.user_email);
$('input[name=txtUserPassword]').val(data.user_password);
$('input[name=txtId]').val(data.id);
},
error: function() {
alert('Could not Edit Data');
}
});
});
//delete
$('#showdata').on('click', '.item-delete', function () {
var id = $(this).attr('data');
$('#deleteModal').modal('show');
$('#btnDelete').unbind().click(function () {
$.ajax({
type: 'ajax',
method: 'get',
async: false,
url: '<?php echo base_url() ?>employee/delete_user',
data: {id: id},
dataType: 'json',
success: function (response) {
if(response.success){
$('#deleteModal').modal('hide');
$('.alert-success').html('User deleted successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function () {
alert('Error deleting');
}
});
});
});
//function
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>employee/showAllEmployee',
async: false,
dataType: 'json',
success: function (data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>'+data[i].id+'</td>'+
'<td>' + data[i].firstname + '</td>' +
'<td>' + data[i].lastname + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].user_email + '</td>' +
'<td>' +
'Edit' +
'Delete' +
'</td>' +
'</tr>';
}
$('#showdata').html(html);
},
error: function () {
alert('Could not get Data from Database');
}
});
}
});
</script>
</div>
<div class="col-sm-3">
<?php
echo "Hello <b id='welcome'><i>" . $username . "</i> !</b>";
echo "<br/>";
echo "Your ID is " . $id;
echo "<br/>";
?>
Logout
</div>
<?php $this->load->view('components/page_tail'); ?>
You need to fetch that user details to index page to avoid edting for other or need to set some condition such as passing users id on edit check if it same as edit id and then proceed for edit opertaion or else return some message