codeigniter:how to check user name and password - ajax

if login failed then how to redirect same login page & display wrong username
$('#login_form').submit(function (e)
{
e.preventDefault();
var uname = $('#uname').val();
var upassword = $('#upassword').val();
if (uname == "" || upassword == "")
{
$('#errmessage').show().html('All Fields are required');
} else {
$('#errmessage').html("").hide();
$.ajax({
type: "POST",
url: "User_controller/login_autho/",
datatype: 'json',
data: {uname: uname, upassword: upassword},
success: function (data) {
$('#successmessage').fadeIn().html(data),
window.location.replace("/User_controller/profile");
}
});
}
});
To check login autho and if success then redirect to profile page
public function login_autho() {
$data = array(
'uname' => $this->input->post('uname'),
'upassword' => $this->input->post('upassword')
);
$result = $this->login_model->login_user($data);
if ($result == TRUE) {
$this->session->set_flashdata('success', 'Success Login');
$this->load->view('user/success');
// echo 'su';
} else {
//$this->session->set_flashdata('error', 'Invalid Username or Password');
//echo 'invalid user';
// echo json_encode(false);
}
}
public function profile() {
$this->load->view('header');
$this->load->view('user/success');
}

Simple to write on
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
Pass these variables to model function
$this->Model->login($uname,$upassword); // Login method you have to create
if($query->count() ==1 ){
echo 'login';
}else{
echo "failed";
}
Then check in database
$query = $this->db->query('SELECT * FROM 'your_table_name' WHERE 'uname'= $uname AND 'password' = $upassword '); // Query modify as per ur requirement
return $query->count();

Controller
$uname = $this->input->post('uname');
$upassword = $this->input->post('upassword');
$result= $this->Model->login($uname,$upassword); // Login method you have to create
if($result=='login'){
header('location:dashbord.php');
} else {
header('location:index.php?error=1');
}
Modal
public function login($uname,$upassword){
$query = $this->db->query('SELECT * FROM 'your_table_name' WHERE uname='. $uname. ' AND password='. $upassword); // Query modify as per ur requirement
if(count($query) ==1 ){
echo 'login';
}else{
echo "failed";
}
}

Related

codeigniter: login form using ajax probelm

This is my login code in codeigniter...its not getting logged in only it shows the result in jquery response?whats wrong with this code?
I have written controller,model and have used jquery for this.
controller(login.php)page
function validate_credentials(){
$username = $this->input->post('username');
$password = $this->input->post('passwd');
$data = $this->login_model->validate();
if($data){
$this->session->set_userdata('username',$data);
redirect('site/math_page');
}
else{
echo'something went wrong';
}
}
Model(login_model.php)page
function validate() {
$this->db->select('*');
$this->db->from('user_details');
// $this->db->where('user_email',$email);
// $this->db->where('user_password',$pass);
if($query=$this->db->get())
{
return $query->result_array();
}
else{
return false;
}
}
login jquery
$(document).ready(function() {
//login js..
$("#login_submit").click(function(){
var username = $("#username").val().trim();
var passwd = $("#passwd").val().trim();
//alert(username);
if( username == "" && passwd == "" ) {
$(".lognerror").html("Please enter Login credentials!");
$(".lognerror").show().fadeOut(3000);
}
else if( username == "" ) {
$(".usererror").html("Please enter username");
$(".usererror").show().fadeOut(3000);
}
else if ( passwd == "" ) {
$(".passwrderr").html("Please Enter Password");
$(".passwrderr").show().fadeOut(3000);
}
else {
$.ajax({
url: base_url+'index.php/login/validate_credentials',
data:{username:username,passwd:passwd},
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
// do something with the result
//var msg = "";
//alert(msg);
if(response == 1){
window.location.href= base_url+'index.php/site/math_page';
}
else {
msg = "Invalid Login credentials!";
}
//$("#message").html(msg);
$("#message").show().fadeOut(3000);
}
});
}
});
});
can someone tell me what's wrong with this code.I am new to php so kindly guide me through this
Send $username and $password as a parameter in validate(). And apply where clause in the model. And use $query->num_rows() > 0 in IF condition.
In Model -
function validate($email, $pass) {
$this->db->select('*');
$this->db->from('user_details');
$this->db->where('user_email',$email);
$this->db->where('user_password',$pass);
$query=$this->db->get()
if($query->num_rows() > 0) {
return $query->result_array();
}
else{
return false;
}
}
In Controller -
Replace
$data = $this->login_model->validate();
With
$data = $this->login_model->validate($username, $password);
Change your response in controller
if($data){
$this->session->set_userdata('username',$data);
echo 1;
}
else{
echo 0;
}

Codeigniter 3 validation error not showing along with callback function

I want to validate login form with ajax. I am using form valiation with a callback function that check username in database. When I am using callback with set_message, form validation errors are not working, only that callback error message is shown. If username is empty then form validation error like "Username is required" should be shown first and then if user enter wrong username then callback function error like "Username is not correct" should be shown
Following are the functions in my controller
public function validate_form()
{
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|callback_password_check');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run()) {
$data['success'] = true;
$this->session->set_userdata('admin_username', $this->input->post('username'));
} else {
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
public function username_check()
{
$username = $this->input->post("username");
if ($this->admin_model->usernameDB()) {
return true;
} else {
$this->form_validation->set_message('username_check', 'The {field} is not correct');
return false;
}
}
public function password_check()
{
$password = $this->input->post("password");
if ($this->admin_model->passwordDB($password)) {
return true;
} else {
$this->form_validation->set_message('password_check', 'The {field} is not correct');
return false;
}
}
Following are the function in my model
public function usernameDB() {
$this->db->where('username', $this->input->post('username'));
$query = $this->db->get('adminuser');
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
public function passwordDB() {
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('adminuser');
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
Following is the ajax that i am using
$("#admin_login_form").submit(function(e) {
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax ({
url: "validate_form",
type: "post",
data: me.serialize(),
dataType: "json",
success: function(response) {
if (response.success == true) {
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
window.location = "member";
} else {
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value);
});
}
}
});
});
I want proper validation errors order like if username or password is empty then first their relevant errors should be shown like username or password is required and then wrong or correct username or password errors should be shown.
You can try below. You can use single callback function to check whether user is exists or not.
First, remove the callback functions public function username_check() and public function password_check() from your controller and replace with the updated functions below.
In addition to this created new model function login inside admin_model which will check whether user is exists or not. Also you can delete both usernameDB and passwordDB from your admin_model.
Controller function:
public function validate_form()
{
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|xss_clean|is_user_exists');
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run()) {
$data['success'] = true;
$this->session->set_userdata('admin_username', $this->input->post('username'));
} else {
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
public function is_user_exists()
{
if ($this->admin_model->login($this->input->post('username', TRUE), $this->input->post('password', TRUE))) {
return true;
} else {
$this->form_validation->set_message('is_user_exists', 'Login failed. Username or password is incorrect');
return false;
}
}
Model function:
public function login($username, $password)
{
$this->db->where('username', $username);
$this->db->where('password', md5($password));
$query = $this->db->get('adminuser');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
Note: Using md5 for encrypt password is not good. See Alex's comment for more details.

codeigniter foreach not displaying all records in table

Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached

Codeigniter form validation with ajax

I want to have a comments box in my website using codeigniter with Ajax. I want if the comment success show new comment. Else show validation error. How to do it?
This is my controller form validation
if ($this->form_validation->run() == TRUE) {
$this->load->model('comment_model');
$this->load->model('user_model');
if($this->comment_model->insert_comment())
{
$data['user_comment']= $this->user_model->get_user_session($this->session->userdata('user_id'));
$data['new_comment']= $this->comment_model->get_one_comment();
$this->load->view('user/insert_comment',$data);
}
} else {
echo validation_errors();
}
This is my ajax success function.
success: function (data) {
if (data)// this is what is need. How to make a if condition
{
$('ol#update').prepend(data);
$('ol#update li:first').slideDown('slow');
}
else
{
$('#myerror1').html(data);
}
}
Return answer from controller as Json and parse it in success function.
if ($this->form_validation->run() == TRUE) {
$this->load->model('comment_model');
$this->load->model('user_model');
if($this->comment_model->insert_comment()) {
$data['user_comment']=$this->user_model->get_user_session($this->session->userdata('user_id'));
$data['new_comment']= $this->comment_model->get_one_comment();
// third argument means, return template as string instead of echo.
$data = $this->load->view('user/insert_comment',$data, TRUE);
$array = array();
$array['success'] = true;
$array['data'] = $data;
} else {
$array = array();
$array['success'] = false;
$array['data'] = validation_errors();
}
echo json_encode($array);
}
And in success function:
success: function (data) {
var jsonData = JSON.parse(data);
if (jsonData.success == true) {
$('ol#update').prepend(jsonData.data);
$('ol#update li:first').slideDown('slow');
} else {
$('#myerror1').html(jsonData.data);
}
}

$this->form_validation->run() not executing

I have an issue in codeignitor form handling it does not execute $this->form_validation->run() on local server. But it does work very fine on live server. I can't find out what is the reason. Here is my controller.
class Login extends CI_Controller
{
function __construct(){
parent::__construct();
}
function removeUser($record_id){
$a = new Alumni();
$a->removeConnections($record_id);
}
function index(){
$redir = isset($_GET['redir'])?$_GET['redir']:'admin';
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('admin');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/login/send_again/');
} else {
//
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
//var_dump($login);
} else {
$login = '';
}
//var_dump($this->input->post("remember"));
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
if ($this->form_validation->run() === false) {
}else{
echo " logged in";// validation ok
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
//echo $loginID;
if ($this->tank_auth->login(
$loginID,
$pass,
$remember,
$data['login_by_username'],
$data['login_by_email'])) { // success
echo "success";
redirect($redir);
} else {
$errors = $this->tank_auth->get_error_message();
//echo "error";
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
.....
Sorry for long code please help me.
I don't see the library getting loaded in your constructor
public function __construct()
{
parent :: __construct();
$this->load->helper('url');
$this->load->helper('cookie');
//load the validation library
$this->load->library('form_validation');
$this->load->library("pagination");
}

Resources