clear form and show new comment jquery php - javascript

I'm trying to do a comment form, that puts the comment in my mysql database, and puts the new comment on my page right after submitting (and clears the form). But somehow you have to always refresh to see the new comments and if you click on submit more than once it shows duplicated comments after refresh. How can I solve that problem? I'm kinda a noob, so my codes are mostly from tutorials that I don't fully understand yet...
my php-page:
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
include "connect.php";
include "comment.class.php";
$comments = array();
$result = mysql_query("SELECT * FROM comments ORDER BY id ASC");
while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Bausatz</title>
<meta name="" content="">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/modernizr-2.7.1.min.js"></script>
<style type="text/css"></style>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400' rel='stylesheet'
type='text/css'>
</head>
<body>
<header>
<div class="logo">
<span class="col">ON THE </span>W<span class="col">OODWAY</span>
</div>
<nav>
TRAVELS
BLOG
ME
</nav>
</header>
<div class="main">
<div class="contentwrapper">
<div class="entry">
</div>
<div class="comment">
<div id="each">
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="post" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="email">Your Email</label>
<input type="text" name="email" id="email" />
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" >
</div>
</form>
</div>
</div>
</div>
</div>
<div class="unten">
<nav>
contact
copyright
</nav>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.9.1.min.js">
<\/script>')</script>
<script type="text/javascript" src="js/comment.js"></script>
</body>
</html>
jQuery:
$(document).ready(function(){
var working = false;
$('#addCommentForm').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('span.error').remove();
/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
if(msg.status){
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
}
else {
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');
});
});
comment.class.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
/*
/ The constructor
*/
$this->data = $row;
}
public function markup()
{
/*
/ This method outputs the XHTML markup of the comment
*/
// Setting up an alias, so we don't have to write $this->data every time:
$d = &$this->data;
$link_open = '';
$link_close = '';
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
return '
<div class="comment">
<div class="name">'.$link_open.$d['name'].$link_close.'</div>
<div class="date" title="Added at '.date('H:i \o\n d M
Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
public static function validate(&$arr)
{
/*
/ This method is used to validate the data sent via AJAX.
/
/ It return true/false depending on whether the data is valid, and populates
/ the $arr array passed as a paremter (notice the ampersand above) with
/ either the valid input data, or the error messages.
*/
$errors = array();
$data = array();
// Using the filter_input function introduced in PHP 5.2.0
if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
{
$email = '';
}
// Using the filter with a custom callback function:
if(!($data['body'] =
filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))) )
{
$errors['body'] = 'Please enter a comment body.';
}
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}
if(!empty($errors)){
// If there are errors, copy the $errors array to $arr:
$arr = $errors;
return false;
}
foreach($data as $k=>$v){
$arr[$k] = mysql_real_escape_string($v);
}
$arr['email'] = strtolower(trim($arr['email']));
return true;
}
private static function validate_text($str)
{
if(mb_strlen($str,'utf8')<1)
return false;
$str = nl2br(htmlspecialchars($str));
$str = str_replace(array(chr(10),chr(13)),'',$str);
return $str;
}
}
?>
submit.php
<?php
error_reporting(E_ALL^E_NOTICE);
include "connect.php";
include "comment.class.php";
$arr = array();
$validates = Comment::validate($arr);
if($validates)
{
mysql_query(" INSERT INTO comments(name,url,email,body)
VALUES (
'".$arr['name']."',
'".$arr['url']."',
'".$arr['email']."',
'".$arr['body']."'
)");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
}
else
{
echo '{"status":0,"errors":'.json_encode($arr).'}';
}
?>
connect.php
<?php
$db_host = '*****';
$db_user = '*****';
$db_pass = '*****';
$db_database = '*****';
$link = #mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_query("SET NAMES 'utf8'");
mysql_select_db($db_database,$link);
?>

Why don't you try appending it to the rest of the comments?
Change this:
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
To this:
$(msg.html).hide().appendTo('#each').slideDown();

Related

can't send messages and $username isn't displayed

I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>&period; Image Dump&period;&period;&period;</p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">😀</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="↑" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.

Im trying to move the same value from page to another in php

I want to move a value from page stepone php to page steptwo php
the value is generated automatically by js on stepone php,
and then I want to use the same value ( id for the submission ) on steptwo php
any ideas ?
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="action_pageone.php" method="POST">
<label for="FullName">Full Name</label><br>
<input type="text" id="FullName" name="FullName"><br>
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
<input type="submit" value="Submit">
</form>
<script>
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ID").value = randomNumber(9);
};
</script>
</body>
</html>
and the action_pageone here it is
so i need to copy this ID to the other page mentioned ( steptwo)
the exact ID
<?php
$ID = $_POST['ID'];
$FullName = $_POST['FullName'];
// Database Connection
$servername = "localhost";
$username = "";
$password = "";
$db = "";
$conn = new mysqli('localhost', 'username', 'password', 'db') or die($conn->connect_error);
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into Registration(ID,FullName) values('$ID','$FullName')";
if ($conn->query($sql) === TRUE) {
header('location: steptwo.php');
} else {
echo " Registration not Success ";
}
$conn->close();
?>
any suggestions guys ?
for me it doesnt matter if its js or php , i need it to work :(
You can use the Web Cache,like cookie or session,then use the php to read this ID value.
there is many ways to do it
use input type hidden and keep pushing it on submit buttons
pass it in URL like google.com?id=2&name=mike and fetch it using $_GET['id']
keep it in session/cookie/js webstorage
You can do this in 2 ways, use hidden form and submit it or use ajax to post it.
hidden form
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="action_pageone.php" method="POST" name="form1">
<label for="FullName">Full Name</label><br>
<input type="text" id="FullName" name="FullName"><br>
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
<input type="button" onclick = "submit()" value="Submit">
</form>
<form action="action_pagetwo.php" method="POST" name="form2">
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
</form>
<script>
function submit()
{
document.forms['form1'].submit();
document.forms['form2'].submit();
//wait what form to submit?.. confused...? yes me 2 lol
}
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ID").value = randomNumber(9);
};
</script>
</body>
</html>
This might a way to achieve what you want but might be inappropriate as after the form gets submitted it actually redirects to the action page. But still you can sort out how you want your response by yourself.
Ajax (after receiving ID in your first php file you pass it to the second one)
<?php
$ID = $_POST['ID'];
$FullName = $_POST['FullName'];
if($ID != NULL)
echo '<script>
$.ajax({
url: "action_pagetwo.php",
type: "post",
data: {
id: '.$ID.'
},
success: function(result) {
console.log("done bro");
}
});
</script>';
// Database Connection
$servername = "localhost";
$username = "";
$password = "";
$db = "";
$conn = new mysqli('localhost', 'username', 'password', 'db') or die($conn->connect_error);
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into Registration(ID,FullName) values('$ID','$FullName')";
if ($conn->query($sql) === TRUE) {
header('location: steptwo.php');
} else {
echo " Registration not Success ";
}
$conn->close();
?>
You can pass the ID in your html page itself to both php files, but you should choose what you want, you want to pass it without redirecting or you wanna direct to page by submitting.

How to pass variables to another php file?

I have a PHP file "login.php" That is being called in a html using a js but the elements doesnt pass the variables to another php file "ucheck_com.php" Where it will perform the validations etc. is there an alternative way to do this?
sample.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="displaylogin"></div>
</body>
</html>
<script>
$(document).ready(function() {
$(function(){
$("#displaylogin").load("user/login.php");
});
});
</script>
login.php:
<?php
require_once 'userphp/connect.php';
require_once 'userphp/ucheck_com.php';
require_once 'userphp/errors.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" lang="en-US">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title></title>
</head>
<body>
<div class="page-container">
<form action="" method="post" class="main">
<label>Alias</label>
<input type="text" name="alias" value="">
<label>Password</label>
<input type="password" name="password">
<br />
<input type="submit" name="login_user" id="login_user" value="Login">
</form>
</div>
</body>
</html>
ucheck_com.php:
if (isset($_POST['login_user'])) {
$alias = mysqli_real_escape_string($connect, $_POST['alias']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$_SESSION['alias'] = $alias;
$_SESSION['password'] = $password;
if (empty($_SESSION['alias'])) {
array_push($errors, "Alias is required");
}
if (empty($_SESSION['password'])) {
array_push($errors, "Password is required");
}
if(count($errors) == 0) {
$result = mysqli_query($connect, "SELECT * FROM `user` WHERE `alias` = '$alias' AND `password` = '$password'");
foreach ($result as $item) {
$_SESSION['email_add'] = $item['email_add'];
$_SESSION['user_id'] = $item['user_id'];
}
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 1) {
header("location: ../index.html");
} else {
array_push($errors, "Wrong alias/password combination");
}
}
}
When you use $_SESSION you need to open the session in the following manner:
session_start();

Codeigniter: login as admin user and login as employee user

Hi I'm currently working on codeigniter framework and I'm currently working on a project which is basically an admin/employee login system.
Currently I have been able to create a login form, and can successfully get a user to login, after having checked the user exists.
I just wanted to be pointed in the right direction as to how I could go about this to be able to login an employee user to an employees page, and an admin user to an admin page.
This is what I have at the moment, which is fully functioning using bootstrap as a front end framework. But allows any user to login.
By the way I have only one table name "employees" which consist only for employee user and admin user from mysql database.
Here is the view: (login.php)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=1,initial-scale=1,user-scalable=1" />
<title> Login Form </title>
<link href="http://fonts.googleapis.com/css?family=Lato:100italic,100,300italic,300,400italic,400,700italic,700,900italic,900" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/styles.css" />
<script src="<?php echo base_url()?>assets/js/bootstrap.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<script>
$(document).ready(function () {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
switch (e.srcElement.id) {
case "username":
e.target.setCustomValidity("Username cannot be blank");
break;
case "pass":
e.target.setCustomValidity("Password cannot be blank");
break;
}
}
};
elements[i].oninput = function (e) {
e.target.setCustomValidity("");
};
}
})
</script>
<style type="text/css">
.back{
position: absolute;
bottom: 0px;
left: 0px;
}
</style>
<section class="container">
<section class="login-form">
<form class="form-signin" action="goClock" method="post" role="login">
<img src="<?php echo base_url()?>assets/images/easypay.png" class="img-responsive center-block" alt="" />
<input type="text" class="form-control input-lg" placeholder="username" name='user' required id="username" autocomplete="off" autofocus />
<input type="password" class="form-control input-lg" placeholder="Password" name='password' required id="pass" required />
<?php
if(!empty($login_error)) {
echo $login_error;
}
?>
<button name='login' class="btn btn-lg btn-block btn-primary" value=" LOGIN " type="submit" id="button2">Login</button>
</form>
<p class="text-center" style="font-weight: bold; font-size: 60;" id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</section>
</section>
<div class="back">
<input class="btn btn-warning" action="action" type="button" value="<- Back" onclick="location.href = 'index';" />
</div>
</body>
</html>
Here is the controller: (home.php)
public function goClock($message = null) {
$this->load->view('imports/header');
$this->load->view('imports/menu');
if (!is_null($this->input->post('login'))) {
$username = $this->input->post('user');
$password = $this->input->post('password');
$userdata = $this->model_home->get_userinfo($username, $password);
$_SESSION['is_loggedin'] = true;
if ($userdata !== false) {
$this->session->set_userdata($userdata);
redirect('home/goHome');
}else {
$data['login_error'] = '<p style="font-size: 16px; color: red;" align="center">Invalid Username or Password</p>';
$this->load->view('login', $data);
}
}else {
$data['username'] = $this->input->post('user');
$data['password'] = $this->input->post('password');
$this->load->view('clock', $data);
}
}
And finally here is the model: (model_home.php)
public function get_userinfo($username = null, $password = null) {
if ($username && $password) {
$this->db->select('username, password, empnum');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->result_array()[0];
}
}
return false;
}
Just to clarify I have only one controller, my main controller by default which is home.php. In conclusion my aim is to be able to redirect an admin user to admin.php and to be able to redirect a employee user to employee.php (Hasn't been created yet).
P.S I already have a column in my table in PhpMyAdmin called "employees".
Please help me. Thank you in advance.
you should add one extra column in Database named as user_type and Set default value=0 for that and for "admin" set it 1.
Now modify your query like this:
if ($username && $password) {
$this->db->select('username, password, empnum,user_type');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->result_array()[0];
}
}
Now check the $userdata[] array value having user_type key if it is 1 then
$this->load->view('admin', $data);
else he is user_type = 0 which means employee
$this->load->view('employee', $data);
NOTE:I can provide the way but here you have to modify your array key and view name as per the need.
First create a filed with name usertype in your database employees table.
Run this query in your phpMyadmin database
ALTER TABLE `employees` ADD `usertype` ENUM('user','employee') NOT NULL DEFAULT 'user' ;
and add following code on your Model
public function get_userinfo($username = null, $password = null) {
if ($username && $password) {
$this->db->select('username, password, empnum,usertype');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->row();
}
}
return false;
}
And on your controller
public function goClock($message = null) {
$this->load->view('imports/header');
$this->load->view('imports/menu');
if (!is_null($this->input->post('login'))) {
$username = $this->input->post('user');
$password = $this->input->post('password');
$userdata = $this->model_home->get_userinfo($username, $password);
$_SESSION['is_loggedin'] = true;
if ($userdata !== false) {
if($userdata->usertype=='user'){ # if user then redirect to user page
redirect('home/goHome');
}else{
# If employee redirect to admin page
}
}else {
$data['login_error'] = '<p style="font-size: 16px; color: red;" align="center">Invalid Username or Password</p>';
$this->load->view('login', $data);
}
}else {
$data['username'] = $this->input->post('user');
$data['password'] = $this->input->post('password');
$this->load->view('clock', $data);
}
}

PHP messages aren't being written to the log file - tutsplus.com tutorial

tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)

Categories