Codeigniter session with multi-dimensional array - php

Check user credentials from model and set userdata there and user logged in successfully but in view i want to show logged in username.But I can't pass logged in value in view .Always return count value 0 in view file.But I don't know why I can't get value when i call the set session data.Thanks in advance for your help.
My model code:
function auth($email, $password, $remember=false)
{
// make sure the username doesn't go into the query as false or 0
if(!$email)
{
return false;
}
$this->db->select('*');
// $this->db->where('active', 1);
$this->db->where('email', $email);
$this->db->where('password', sha1($password));
$this->db->limit(1);
$result = $this->db->get('guests');
$result = $result->row_array();
if (sizeof($result) > 0)
{
$admin = array();
$admin['front_user'] = array();
$admin['front_user']['id'] = $result['id'];
$admin['front_user']['firstname'] = $result['firstname'];
$admin['front_user']['lastname'] = $result['lastname'];
$admin['front_user']['email'] = $result['email'];
$admin['front_user']['mobile'] = $result['mobile'];
if($remember)
{
$loginCred =
json_encode(
array('username'=>$username, 'password'=>$password));
$loginCred = base64_encode($this->aes256Encrypt($loginCred));
//remember the user for 6 months
$this->generateCookie($loginCred, strtotime('+6 months'));
}
$this->session->set_userdata($admin);
return $admin['front_user'];
return true;
}
else
{
return false;
}
}
And my controller code:
function login(){
//echo '<pre>'; print_r($_POST);die;
$this->load->library('form_validation');
$this->form_validation->set_rules
('email', 'Email', 'trim|required|max_length[32]');
$this->form_validation->set_rules
('password', 'Password', 'required|min_length[4]');
if ($this->form_validation->run() == TRUE)
{
$email = $this->input->post('email');
$password = $this->input->post('password');
return $return = $this->login_model->auth
($email,$password,'','');
if($return){
echo 1;die;
}else{
echo 'Email or Password invalid';
}
}
else{
echo validation_errors();
}
}
And my view file:
<?php
if(count($this->front_user)>0):?>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" >
<?php echo $this->front_user['firstname']?>
</a>
<a href="<?php echo site_url('front/account/logout')?>" >
<i class="fa fa-sign-out pull-left"></i>
<?php echo lang('logout')?>
</a>
<?php endif; ?>
<?php if(count($this->front_user)<1):?>
<a href="#" >
<?php echo lang('login')?>
</a>
<a
<?php echo lang('signup')?></a></li>
<?php endif;
?>
This is my primary view loading method in controller
function index()
{
$data['meta_description'] = $this->setting->meta_description;
$data['meta_keywords'] = $this->setting->meta_keywords;
$data['page_title'] = lang('home');
$data['banners'] = $this->homepage_model->get_banners();
$data['testimonials'] = $this->homepage_model->get_testimonials();
$data['room_types'] = $this->homepage_model->get_room_types();
$data['coupons'] = $this->homepage_model->get_coupons();
//$data['testimonials'] = $this->testimonial_model->get_all();
//echo '<pre>'; print_r($data['coupons']);die;
$this->render('homepage/homepage', $data);
}
And I send login credentials via ajax request and get value into that
view via ajax
$( "#signinForm" ).submit(function( event ) {
event.preventDefault();
var form = $(form).closest('form');
call_loader();
$.ajax({
url: SITE_URL+'/front/homepage/login',
type:'POST',
data:$("#signinForm").serialize(),
success:function(result){
//alert(result);return false;
console.log(result);
if(result==1)
{
toastr.success('You Logged In Successfully');
//location.reload();
window.location.reload()
}
else
{
remove_loader();
toastr.error(result);
//$('#err').html(result);
}
}
});
});
this is java script code.

If($this->session->has_userdata($array['front_user']){
echo $this->session->userdata($array['front_user']['first_name']);
}

Related

AJAX code seems to be ok, but it doesn't show anything

So I have a live chat, and when the user clicks the button, this function should kick into action and insert it into the database and into the HTML conversation section.
The first problem is that if i use dataType: "json" , then it enters the AJAX error case instead of success. But if I pull it out, like below, it enters the success case. But here comes the second problem: only the first alert is displayed, and if I try to alert the response, it doesn't show anything (+neither the alert('yes') is displayed).
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
EDIT1:
It might be useful to understand my files:
I have index.php which contains the actual chat. When the send button is clicked, it accesses the chat.js file that contains the script above. Then, this is the part of chat_action.php that deals with it and passes it further to Chat.php.
chat_action.php
session_start();
include ('Chat.php');
$chat = new Chat();
if($_POST['action'] == 'insert_chat') {
$chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']);
}
Chat.php
<?php
class Chat{
private $host = 'localhost';
private $user = 'root';
private $password = "";
private $database = "chat_demo";
private $chatTable = 'chat';
private $chatUsersTable = 'chat_users';
private $chatLoginDetailsTable = 'chat_login_details';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
public function insertChat($reciever_userid, $user_id, $chat_message) {
$sqlInsert = "
INSERT INTO ".$this->chatTable."
(reciever_userid, sender_userid, message, status)
VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')";
$result = mysqli_query($this->dbConnect, $sqlInsert);
if(!$result){
return ('Error in query: '. mysqli_error($this->dbConnect));
} else {
$conversation = $this->getUserChat($user_id, $reciever_userid);
$data = array(
"conversation" => $conversation
);
echo json_encode($data);
}
}
public function getUserChat($from_user_id, $to_user_id) {
$fromUserAvatar = $this->getUserAvatar($from_user_id);
$toUserAvatar = $this->getUserAvatar($to_user_id);
$sqlQuery = "
SELECT * FROM ".$this->chatTable."
WHERE (sender_userid = '".$from_user_id."'
AND reciever_userid = '".$to_user_id."')
OR (sender_userid = '".$to_user_id."'
AND reciever_userid = '".$from_user_id."')
ORDER BY timestamp ASC";
$userChat = $this->getData($sqlQuery);
$conversation = '<ul>';
foreach($userChat as $chat){
$user_name = '';
if($chat["sender_userid"] == $from_user_id) {
$conversation .= '<li class="replies">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$fromUserAvatar.'" alt="" />';
} else {
$conversation .= '<li class="sent">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$toUserAvatar.'" alt="" />';
}
$conversation .= '<p>'.$chat["message"].'</p>';
$conversation .= '</li>';
}
$conversation .= '</ul>';
return $conversation;
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error($this->dbConnect));
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getUserAvatar($userid){
$sqlQuery = "
SELECT avatar
FROM ".$this->chatUsersTable."
WHERE userid = '$userid'";
$userResult = $this->getData($sqlQuery);
$userAvatar = '';
foreach ($userResult as $user) {
$userAvatar = $user['avatar'];
}
return $userAvatar;
}
}
EDIT2:
From the console:
chat.js:106
index.php:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.success (chat.js:107)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
you try to parsing not valid json, in your js maybe try this:
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
try {
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
} catch(e) { alert(e) }
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}

Json returns undifined

Good day guys I have the following login page. Which I access using ajax from my view page. The problem the data that is returned when I try to display on ajax I get an error on the console.
login.js:35 Uncaught TypeError: Cannot read property 'success' of
undefined
at Object.success (login.js:35)
at i (jquery-2.2.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.2.0.min.js:2)
at z (jquery-2.2.0.min.js:4)
at XMLHttpRequest. (jquery-2.2.0.min.js:4)
<?php
ob_start();
function __autoload($classname)
{
require_once("../../database/$classname.php");
}
class userlogin extends database
{
private $errors = array();
private $message = array();
private $redirect = array();
private $data = array();
private $username;
private $password;
function login()
{
if (empty($_POST['username']) || empty($_POST['password'])) {
$this->message['error'] = "Please enter username and password";
} else {
$this->username = $_POST['username'];
$this->password = $_POST['password'];
try {
$this->stmt = $this->dbh->prepare("SELECT adminID,adminEmail,adminPassword,admintype FROM admin where adminEmail = ? ");
$this->stmt->execute(array(
$this->username
));
$this->results = $this->stmt->fetchall();
if (count($this->results) > 0) {
foreach ($this->results as $key => $row) {
if (password_verify($this->password, $row['adminPassword'])) {
$_SESSION['user'] = $row['adminID'];
$_SESSION['email'] = $this->username;
$_SESSION['usertype'] = $row['admintype'];
switch ($row['admintype']) {
case 's':
$this->redirect['redirect'] = "seo/index.php?route=home";
break;
case 'a':
$this->redirect['redirect'] = "admin/index.php?route=home";
break;
}
$this->message['success'] = "ok";
} else {
$this->message['error'] = "Username and password does not match";
}
}
} else {
$this->message['error'] = "Username does not exist";
}
}
catch (PDOException $pdo) {
$this->error = $pdo->getMessage();
error_log($this->error);
}
$this->data['message'] = $this->message;
$this->data['redirects'] = $this->redirect;
ob_end_clean();
echo json_encode($this->data);
}
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$login = new userlogin();
$login->login();
}
?>
and my js
function proccessLogin(){
var username = $('input[type="email"][name="email"]').val();
var password = $('input[type="password"][name="upass"]').val();
$.ajax({
type : "POST",
data : {username:username,password:password},
url : "controller/login.php",
beforeSend : function(){
$('button').html('Checking...');
},
success : function(data){
console.log(data);
if(data.message.success == "ok"){
$('#results').removeClass('error');
$('#results').addClass('success');
$('#results').html('login Success, loading user data..');
$('button').html('Loading Profile.. i class="fa fa-spinner fa-pulse fa-1x fa-fw"></i>');
var redirectUrl = JSON.stringify(data.redirects);
redirectUrl = redirectUrl.replace(/[{"":}]/g, '');
var url = redirectUrl.replace('redirect','');
setTimeout(' window.location.href = "'+ url + '"; ', 6000);
}else{
$('button').html("Sign in");
$('#results').removeClass('success');
$('#results').addClass('error');
$('#results').html(data.message.error);
}
},
error : function(xhr){
console.log('Error : ' + xhr);
}
});
return false;
}
Console log results :
{"message":{"success":"ok"},"redirects":{"redirect":"seo\/index.php?route=home"}}
I want to be able to display the message from the json array if success is ok I will display custome message else display what is coming from response. the problem is property undefined.
line 35 :
if(data.message.success == "ok"){
I think the response data is String and you need to call
$.parseJSON(data);
before you can access message and then success
=============
If you want to use dataType: "json", you need to send your JSON as JSON by using PHP's header() function:
/* Send as JSON */
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode($json);
/* Stop Execution */
exit;

user still can login although password and username is wrong

this problem make me confuse why user still can login although username and password is wrong. I don't have any idea in this problem. i try build android with ionic framework
this my controller
**
.controller('LoginCtrl', function ($scope, kaka, $ionicPopup, $state, Varlogin) {
$scope.loginData = {};
$scope.proseslogin = function () {
kaka.loginUser($scope.loginData.username, $scope.loginData.password).success(function (data) {
if (data.length > 0) {
Varlogin.setObject(data[0]);
var alertPopup = $ionicPopup.alert({
title: 'Selamat Datang',
template: 'Perikasa keadaan motor anda!'
});
$state.go('app.home');
} else {
var alertPopup = $ionicPopup.alert({
title: 'Login Gagal!',
template: 'Periksa Username dan Password anda!'
});
}
}).error(function (data) {
});
};
$scope.register = function () {
$state.go('register');
};
})
**
and this my php
**
if($function == "login" ){
$sql = mysqli_query($con, "select * from login where username='$w5'")or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
$pass = $row['hash_password'];
$hash_password = password_verify($w6, $pass);
if($hash_password == TRUE) {
$sqlcode = $con->query("select * from login where username='$w5' AND hash_password='$pash' AND aktif='Y'", MYSQLI_USE_RESULT);
$jsonObj = array();
while ($result = mysqli_fetch_object($sqlcode)) {
$jsonObj[] = $result;
echo "Berhasil";
}
}else {
echo "gagal";
mysqli_close($con);
}
}
**
please help my problem

Can't update DataBase with checkbox data

I have a list of 4 images of an item.
One of them should show up in another page as a link from that page to the item page.
I want to be able to check a box so that this one will be the main pic and will show up in the category page.
this is the code of the form:
$all_pics_of_item = fetch_all_pics_of_item($item_id);
//print_r($all_pics_of_item);
if(is_array($all_pics_of_item))
{
echo '<ul>';
foreach($all_pics_of_item as $key=>$val)
{
if ($val['pics_main']=='yes')
{
$set_checked = "checked";
$action = true;
}
else
{
$set_checked = "";
$action = false;
}
echo '<li style="float: left;margin:10px;border: 1px solid #000;padding:10px;">';
echo '<img style="width:120px;height:120px;" src="../../gallery_images/thumbs/'.$val['pics_source'].'">';
echo '<br>'.$val['pics_name'];
echo '<br><div class="delet"><b>x</b></div>';
echo '<br><form method="post" action="update_main_pic.php" enctype="text/plain" >
Show in cat. page<input type="checkbox" class="myCheckbox" name="main" value="no"'.$set_checked.'&action='.$action.' data-picid="'.$val['pics_id'].'" data-itemid="'.$item_id.'" />
</form>';
echo '</li>';
}
echo '<ul>';
}
Here is the AJAX and script:
$(document).ready(function(){
$(':checkbox').click(function() {
$(':checkbox').not(this).removeAttr('checked');
var picid = $(this).attr('data-picid');
var itemid = $(this).attr('data-itemid');
var action = $(this).is(':checked');
//if((this).attr('checked',true))
//{
// var action = true;
//}
//else
// {
// var action = false;
// }
$.ajax({
url: "ajax_update_main_pic.php",
type: "POST",
data: "itemid=" + itemid + "&picid=" + picid + "&action=" + action,
timeout:5000,
dataType: "html",
beforeSend:function(){
},
error: function(){
alert('Problem !');
},
success: function(msg){
if(msg == 'no')
{
}
else
{
}
},
complete: function(){
}
})
});
}); //END READY
Here is the update function:
<?php
require_once "../../db.php";
require_once "../../functions.php";
if(isset($_POST['itemid']) && isset($_POST['picid']) && isset($_POST['action']))
{
$item_id = $_POST['itemid'];
$pic_id = $_POST['picid'];
$action = $_POST['action'];
}
else
{
header('location: upload_image.php');
die();
}
if($action == 'true')
{
$pic_show = 'yes';
}
else
{
$pic_show = 'no';
}
//print_r($pic_show);
function update_main_pic($item_id, $pic_id, $pic_show )
{
global $db;
try
{
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pics_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_items_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_main', $pic_show, PDO::PARAM_STR);
$stmt->execute();
return true;
}
catch(Exception $e)
{
return false;
}
}
$result = update_main_pic($item_id, $pic_id, $pic_show );
if($result == false)
{
die('Problem updating pics');
}
else
{
header('location: upload_image.php?iid='.$item_id);
die();
}
?>
I always get 'Problem updating pics'
It looks like only the checked checkbox is transmitted, while I want that the column PIC_MAIN will show "yes" if this is the one chosen and "no" foe all other pics
The issue lies with your binding.
You sql has the following name variables :pic_show , :pic_id and :item_id but you are binding :pics_main', :pics_items_id and :pics_id.
Change your binding to:
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pic_show', $pic_show, PDO::PARAM_STR);

Codeigniter ajax(jquery) login session issue?

i m new in Codeigniter and i have created a Login system with jquery in codeigniter. but i m stuck with the session problem. When i will submit the login from i will works perfectly and create the session perfectly but when it will redirect to the next page after login the session will destroyed automatically and it will come back to the login page all the time.
Can any one help to what to do in that??
My code is below
Admin Controller
<?php
class Admin extends CI_Controller {
function index()
{
$data['title'] = 'Admin Panel';
$this->load->helper('auth');
if(is_admin_loggedin(0)){ // Check if is login
//To display Dashboard Page
$this->load->view('admin/index', $data);
}else{
//To display Login Page
$this->load->view('admin/login/index', $data);
}
}
function login_action(){
$this->load->model('login_model');
$query = $this->login_model->check_login();
if($query){
$data = array(
'adminid' => $query[0]['AdminID'],
'is_logged_in' => true
);
$this->load->library('session');
$this->session->set_userdata($data);
print_r($this->session);
exit;
//redirect('admin');
$success = true;
$success_redirect = true;
$success_msg = site_url('admin');
$error = false;
$error_msg = '';
}else{
$success = false;
$success_redirect = false;
$success_msg = site_url('admin');
$error = true;
$error_msg = 'Error, Wrong username or password!';
}
$passstring = array(
'success' => $success,
'success_msg' => $success_msg,
'success_redirect' => $success_redirect,
'error' => $error,
'error_msg' => $error_msg
);
echo json_encode($passstring);
}
}
?>
i have created the auth helper file for checking the login is set or not.
auth_helper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('is_admin_loggedin'))
{
function is_admin_loggedin($reval){
// Get current CodeIgniter instance
$CI =& get_instance();
// We need to use $CI->session instead of $this->session
$adminid = $CI->session->userdata('adminid');
$is_logged_in = $CI->session->userdata('is_logged_in');
if($reval == 1){
return $CI->session;
}else{
if(!isset($is_logged_in) || $is_logged_in != true || !isset($adminid) || $adminid != '')
{
return false;
}else{
return true;
}
}
}
}
?>
login_model.php
<?php
class Login_Model extends CI_Model{
public function __construct()
{
$this->load->database();
}
public function check_login(){
//$this->form_validation->set_rules('username', 'User Name', 'trim|required');
//$this->form_validation->set_rules('password', 'Password', 'trim|required');
//if($this->form_validation->run() == FALSE){
$this->db->where('UserName', $this->input->post('username'));
$this->db->where('Password', md5($this->input->post('password')));
$this->db->select('AdminID');
$query = $this->db->get('admin');
if($query->num_rows == 1)
{
return $query->result_array();
}
//}
}
}
?>
My view file Code
<form action="<?php echo base_url();?>index.php/admin/login_action" method="post" name="LoginAdmin" id="LoginAdmin" >
<div class="error-container hide"></div>
<div class="login-box-row-wrap corners">
<label for="username">Username:</label><input type="text" id="username" value="" name="username" class="input-1"/>
</div>
<div class="login-box-row-wrap corners">
<label for="password">Password:</label> <input type="password" id="password" value="" name="password" class="input-1 password"/>
</div>
<div class="login-box-row corners">
<input type="checkbox" name="remember" id="field-remember"/> <label for="field-remember">Remember me?</label>
<input type="submit" name="submitfrm" value="Login" id="submit"/>
</div>
</form>
<script type="text/javascript" language="javascript">
$(document).ready(function (){
var LoginID = '#LoginAdmin';
$(LoginID).submit(function(){
var errorselector = LoginID+' .error-container';
$(errorselector).html('').hide();
var username = $('#username').val();
var paossword = $('#password').val();
var isValid = 0;
var errmsg = '';
if(!checkblank(username) || !checkblank(paossword)){
errmsg = 'Please fill all the fields.';
isValid = 1;
}
if(isValid == 0){
$('.loader').show();
var urlred = $(this).attr('action');
$.ajax({
type: "POST",
url: urlred,
data: $(this).serialize(),
dataType: "json",
success: function(msg){
console.log(msg);
$('.loader').hide();
if (msg.success == false && msg.error == true) {
if(msg.error_msg != ''){
errormsg = msg.error_msg;
}else{
errormsg = 'Error, Something Worong';
}
$msgdis = '<div class="login-box-error-small corners"><p>'+errormsg+'</p></div>';
$(errorselector).html($msgdis).slideDown('slow');
}else if (msg.success == true && msg.error == false) {
if(msg.success_redirect == true){
window.location = msg.success_msg;
}else{
$msgdis = '<div class="login-box-succes-small corners"><p>'+msg.success_msg+'</p></div>';
$(errorselector).html($msgdis).slideDown('slow');
}
}
$(this).find('button.submitbutton').attr('disabled', '');
},
error: function(){
$('.ui-dialog-titlebar #ui-dialog-title-dialog').html('Error');
$('#dialog_text').html("There was an error submitting the form. Please try again.");
$('#dialog').dialog('open');
$(this).find('button.submitbutton').attr('disabled', '');
}
});
}else{
$msgdis = '<div class="login-box-error-small corners"><p>Error, '+errmsg+'</p></div>';
$(errorselector).html($msgdis).slideDown('slow');
}
//make sure the form doesn't post
return false;
});
});
</script>
Thanks
In your controller in function login_action() remove exit. You stopped script so $passstring will never be set.
so this function should look like that:
function login_action(){
$this->load->model('login_model');
$query = $this->login_model->check_login();
if($query){
$data = array(
'adminid' => $query[0]['AdminID'],
'is_logged_in' => true
);
$this->load->library('session');
$this->session->set_userdata($data);
print_r($this->session);
//exit; <-- remove this
//redirect('admin');
$success = true;
$success_redirect = true;
$success_msg = site_url('admin');
$error = false;
$error_msg = '';
}else{
$success = false;
$success_redirect = false;
$success_msg = site_url('admin');
$error = true;
$error_msg = 'Error, Wrong username or password!';
}
$passstring = array(
'success' => $success,
'success_msg' => $success_msg,
'success_redirect' => $success_redirect,
'error' => $error,
'error_msg' => $error_msg
);
echo json_encode($passstring);
}

Categories