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();
Related
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>. Image Dump...</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.
So, I am trying to retrieve data from my mysql database after a user registers or logins. The thing is that it somehow retrieves the letter "u" and that's weird, because there is no place that contains the letter "u".
This is the result I am getting as of now
https://imgur.com/t3XBrPN
index.php(where user registers or logs in)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function start(){
closeForm();
closeRegForm();
}
function openForm() {
document.getElementById("myForm").style.display = "block";
closeRegForm();
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
function openRegForm() {
document.getElementById("myRegForm").style.display = "block";
closeForm();
}
function closeRegForm() {
document.getElementById("myRegForm").style.display = "none";
}
</script>
</head>
<body onload="start()">
<nav>
<button class="button" type="submit" onclick="openForm()">Влез</button>
<button class="buttonReg" type="submit" onclick="openRegForm()">Регистрирай се</button>
<img src="Logo4.png" class="Logo" alt="Logo">
</nav>
<div class="form-popupRegister" id="myRegForm">
<form method="post" action="server.php" class="form-containerReg">
<h1>Регистрирация</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">
<label for="email"><b>Е-майл</b></label>
<input type="email" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">
<label for="password_1"><b>Парола</b></label>
<input type="password" placeholder="Въведете парола" name="password_1">
<label for="password_2"><b>Повторете Парола</b></label>
<input type="password" placeholder="Въведете парола повторно" name="password_2">
<button type="submit" class="btnReg" name="reg_user">Register</button>
<button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
</form>
</div>
<div class="form-popup" id="myForm">
<form method="post" action="server.php" class="form-container">
<h1>Влизане</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" value="<?php echo $username; ?>">
<label for="password"><b>Парола</b></label>
<input type="password" name="password">
<button type="submit" class="btn" name="login_user">Login</button>
<button type="button" class="btn-cancel" onclick="closeForm()">Close</button>
</form>
</div>
</body>
</html>
index2.php(where the data should be output)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function getUserStats(){
<?php
$queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
$userStats = mysqli_query($db,$queryThree);
$userStatsTwo = mysqli_fetch_assoc($userStats);
?>
}
</script>
</head>
<body onload="getUserStats()">
<div class="navWrapper">
<div class="statistics">
<div class="profilePicture" name="profilePicture">
<label class="profilePictureLabel" for="profilePicture"><b><?php echo userStatsTwo['username']; ?></b></label>
</div>
<div class="money" name="money">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['money']; ?></b></label>
</div>
<div class="diamond" name="diamond">
<label class="diamondLabel" for="diamond"><b><?php echo userStatsTwo['diamonds']; ?></b></label>
</div>
<div class="ruby" name="ruby">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['ruby']; ?></b></label>
</div>
<div class="level" name="level">
<label class="levelLabel" for="level"><b>Level:<?php echo userStatsTwo['level']; ?></b></label>
</div>
</div>
</div>
</body>
</html>
server.php(where the data is being processed)
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$idQuery = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'censored', 'id9159890_registerdb');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM `register` WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level)
VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
mysqli_query($db, $query);
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}
}
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM `register` WHERE username='$username'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The results that I should be getting are(from top to bottom and left to right)
Username, Level, Money, Diamond, Ruby and their values should respectively be Username, 0, 0, 0, 0.
I've tried everything and nothing changes, I've re-constructed my code twice and it still outputs only that and nothing else.
You have an issue here in your code:
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
As i mentioned in my comment, check what are you getting in echo "SELECT * FROM register WHERE ID='$idQuery' "; you definitely getting this kind of result:
SELECT * FROM register` WHERE ID= 'SELECT ID FROM `register` WHERE username='somename''
For sub query, remove quotes around your variable from:
"SELECT * FROM register` WHERE ID='$idQuery' ";
should be:
"SELECT * FROM register` WHERE ID = $idQuery";
Note that, this is success case, as you show your result here https://imgur.com/P64hqvI, your query is working fine..
You also need to use some protection for $idQuery if $idQuery == '' then your you can't get any result also.
As #patrick-q mentioned, use session to store username or ID instead of saving a full query.
Second, you code is wide open for SQL injection, for preventing, use PDO.
Some helpful links:
Are PDO prepared statements sufficient to prevent SQL injection?
How can I prevent SQL injection in PHP?
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)
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();
I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("사용가능한 아이디");
idCheck.val('1');
}
else{
alert("다른 아이디 입력");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">중복확인</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>