codeigniter: login form using ajax probelm - codeigniter

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;
}

Related

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.

404 error occur while calling laravel API from ionic

i am trying to call API from ionic but it shows 404 error
here is my code for provider
remoteservice.ts
export class RemoteserviceProvider {
public headers = new Headers( { 'X-API-KEY' :
'xxxxxxxxx' });
public options = new RequestOptions({ headers: this.headers });
constructor(public http: Http) {
console.log('Hello RemoteserviceProvider Provider');
}
rec:any[]=[];
use:any[]=[];
login(credentials) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost/my/v1/adminlogin', credentials,
{headers: this.headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
Login.ts
doLogin() {
this.showLoader();
this.remoteService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.responseData = result;
console.log(this.responseData);
if(this.responseData.message=='Login Success'){
localStorage.setItem('loginData', JSON.stringify(this.responseData));
if(this.responseData.user_type==1){
if(this.responseData.project_type==null){
this.presentToast('You are not assigned to any project');
}
else{
if(this.responseData.project_type=='Concrete'){
console.log(this.responseData.p_id)
this.navCtrl.setRoot(ConcretePage,
{p_id:this.responseData.p_id, s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else if(this.responseData.project_type=='Bricks'){
this.navCtrl.setRoot(ProductionPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else{
this.navCtrl.setRoot(DailyReportPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
}
My API code is laravel
index.php
<?php
//including the required files
require_once '../include/DbOperation.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->hook('slim.before.dispatch', function () use ($app){
$headers = request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
$api_key = $headers['X-API-KEY'];
// this could be a MYSQL query that parses an API Key table, for example
if($api_key == 'xxxxxxxxxxxxxxx') {
$authorized = true;
} else if ($api_key == NULL) {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key not sent"
}}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
$app->halt(401, $response['message']);
} else {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key invalid" }}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
}
if(!$authorized){ //key is false
// dont return 403 if you request the home page
$req = $_SERVER['REQUEST_URI'];
if ($req != "/") {
$app->halt('403', $response['message']); // or redirect, or
other something
}
}
});
$app->post('/adminlogin', function () use ($app) {
$json = $app->request->getBody();
$input = json_decode($json, true);
$mobile= (int)$input['mobile'];
$password = (string)$input['password'];
$db = new DbOperation();
$response = array();
$response['report'] = array();
if ($db->adminLogin($mobile,$password)) {
$admin = $db->getAdmin($mobile);
$admin1 = $db->getassignedproject($mobile);
$admin2 = $db->getprojecttype($admin1['p_id']);
$admin4 = $db->updateadminlogin($mobile,$password);
$response['error'] = false;
$response['p_id']=$admin1['p_id'];
$response['id'] = $admin['u_id'];
$response['name'] = $admin['username'];
$response['date'] = date('Y-m-d');
$response['user_type'] = $admin['user_type'];
$response['project'] = $admin1['p_name'];
$response['project_type'] = $admin2['p_type'];
$response['location'] = $admin2['location'];
$response['message'] = "Login Success";
} else {
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
echoResponse(200, $response);
});
while am calling API using /adminlogin this shows 404 error
i don't know where i did wrong.
Anyone can please give me some idea to overcome this.
Thanks in Advance

codeigniter:how to check user name and password

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";
}
}

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);
}
}

Check customer email is already exist in magento using ajax prototype

I want to check customer email is already exist or not using ajax prototype. I tried lots of things but it is not working. I write my code like this.
<script type="text/javascript">
//<![CDATA[
var dataForm = new VarienForm('form-validate', true);
Validation.add('validate-emaila', 'Email already exist', function(v) {
var url = '/customer/account/checkEmail/email?email=' + encodeURIComponent(v);
var ok = false;
new Ajax.Request(url, {
method: 'get',
asynchronous: false,
onSuccess: function(transport) {
alert(transport.responseText);
var obj = response = eval('(' + transport.responseText + ')');
validateTrueEmailMsg = obj.status_desc;
if (obj.ok === false) {
Validation.get('validate-email').error = validateTrueEmailMsg;
ok = false;
} else {
ok = true; /* return true or false */
}
},
onFailure: function(){ alert('something wrong') },
onComplete: function() {
if ($('advice-validate-email-email')) {
$('advice-validate-email-email').remove();
}
if ($('advice-validate-email-email_address')) {
$('advice-validate-email-email_address').remove();
}
if ($('advice-validate-email-billing:email')) {
$('advice-validate-email-billing:email').remove();
}
if ($('advice-validate-email-shipping:email')) {
$('advice-validate-email-shipping:email').remove();
}
if ($('advice-validate-email-_accountemail')) {
$('advice-validate-email-_accountemail').remove();
}
}
});
return ok;
});
//]]>
</script>
I called a function In customer/accountcontroller
public function checkEmailAction()
{
$bool = 0;
$email = $this->getRequest()->getParam('email');
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail($email);
if ($customer->getId()) {
$bool = 1;
}
$jsonStatus = 200;
$info = array( "status" => $bool);
$this->getResponse()->setBody(json_encode($info))->setHttpResponseCode($jsonStatus)->setHeader('Content-type', 'application/json', true);
return $this;
}
I am getting wrong response from php function. it is returning full page html. instead of 0 or 1.
I have tried lots of thing but giving same response. Can any one tell me what is wrong in this?
it is wrong code for checking customer.You need to add website id to customer load
First need to change customer check url move from customer accountcontroller.php to checkout onepagecontroller.php. Because magento cannot easly add to accountcontroller.php
url ='<?php echo $this->getUrl('checkout/onepage/checkEmail', array('_secure'=>true)); ?>'
var request = new Ajax.Request(
url,
{
method:'get',
parameters: {email:encodeURIComponent(v)}
onSuccess: function(transport)
{
if(transport.status == 200)
{
var data = transport.responseText.evalJSON();
if(data.success==true){
}
}
}
}
);
In checkout onepagecontroller.phpadd the below code
public function forcecheckAction()
{
$response=array();
$email = $this->getRequest()->getParam('email');
try{
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email); //load customer by email i 
/* if customer has ,then login */
if($customer->getId()>0){
$response['success'] = true;
}else{
$response['success'] = false;
}
}catch(Exception $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
}
$this->getResponse()->setBody(Zend_Json::encode($response));
}

Resources