I have a comment system in which user comments and through ajax it validates the data and sent to .php page. The problem is it receives the status=1 but does not apply the else if Ajax code. I am stuck here. Any suggestions or help will be highly regarded.
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_comment").click(function() {
var proceed = true;
$(" #comment_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed)
post_data = {
'user_email' : $('input[name=email]').val(),
'pid' : $('input[name=productid]').val(),
'msg' : $('textarea[name=comment]').val()
};
$.post('comments.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}
else if(response.status && response.type != 'error')
{
output = '<div class="success">'+response.text+'</div>';
$(response.html).hide().insertBefore('#comment_form').slideDown();
$(" #comment_form textarea[required=true]").val('');
$("#comment_form #comment_body").slideUp();
}
$("#comment_form #comment_results").hide().html(output).slideDown();
}, 'json');
});
//reset previously set border colors and hide all message on .keyup()
$("#comment_form input[required=true], #comment_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Form
<?php
include "comment.php";
$comments = array();
$result = mysqli_query($con,"SELECT * FROM comments where product_id='$id' ORDER BY dt LIMIT 5");
while($row = mysqli_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<?php
}
}
?>
<div class="form-style" id="comment_form">
<div id="comment_results"></div>
<div id="comment_body">
<input type="hidden" name="email" id="email" value="<?php echo $email?>">
<input type="hidden" name="productid" id="productid" value="<?php echo $pid?>" />
<label for="field5"><span>Comment: <span class="required">*</span></span>
<textarea name="comment" id="comment" class="textarea-field" required="true"></textarea>
</label>
<label>
<span> </span><input type="submit" id="submit_comment" value="Submit"">
</label>
</div>
</div>
comment.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
$this->data = $row;
}
public function markup()
{ $d = &$this->data;
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
return '
<div class="comment">
<div class="name">'.$d['email'].'</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>
';
}
}
?>
comments.php
<?php
include("db/db.php");
include "comment.php";
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_email"], FILTER_SANITIZE_STRING);
$pid = filter_var($_POST["pid"], FILTER_VALIDATE_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$arr = array();
//additional php validation
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
mysqli_query($con,"INSERT INTO comments(email,body,product_id) values('$user_name','$message','$pid')");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$res=mysqli_query($con,$query);
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
if(!$res)
{
$output = json_encode(array('type'=>'error', 'text' => 'Cannot recieve your comment.'));
die($output);
}else{
$output= json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your review','status'=>1,'html'=>$insertedComment->markup()));
echo $output;
die($output);
}
}
?>
Related
First of all I must say that I'm very new to website design and coding so please make your answer simple thanks a lot .
So I have my file register.php that contains my form .
I have my action file named register-controller.php that gets the data from user , checks it and inserts it to database .
What I need is that whenever the register is success , my form gets hidden or removed and my new div shows up that contains 'register successful' . ( On the same page "register.php" )
Can I use the variable that I passed to header "register=success" to do this action ? Should I use AJAX ? JSON ? what should I do ? Please give me the simplest answer thank you all .
MY "register.php" file contains these :
<?php
require_once "../DB/users-database.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/Header.CSS">
<link rel="stylesheet" href="/Style.CSS">
<link rel="stylesheet" href="/Footer.CSS">
<script src="https://kit.fontawesome.com/38b3678073.js" crossorigin="anonymous"></script>
<script src="../JS/main.js" async></script>
<title>ثبت نام | PCGA</title>
</head>
<body>
<?php include '../header.php' ?>
<div class="register-container">
<form action="../controllers/register-controller.php" method = "POST">
<label class = "email-label" for="email">ایمیل</label>
<input type="text" id="email" name="email" placeholder="example#example.com" value = '<?php if(isset($_REQUEST['email'])){echo $_REQUEST['email'];}else{echo '';} ?>'>
<?php
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyEmail'){
echo "<span class = 'empty-email'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidEmailFormat') {
echo "<span class = 'formaterr-email'>فرمت ایمیل نادرست است*</span>";
}
?>
<label class = "phone-label" for="phone">شماره موبایل</label>
<input type="text" id="phone" name="phone" placeholder="09xxxxxxxxx" value = '<?php if(isset($_REQUEST['phone'])){echo $_REQUEST['phone'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPhone'){
echo "<span class = 'empty-phone'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidPhoneNumber') {
echo "<span class = 'formaterr-phone'>شماره موبایل حداکثر 11 عدد است و حروف قابل قبول نیست*</span>";
}
?>
<label class = "user-label" for="username">نام کاربری</label>
<input type="text" id="username" name="username" placeholder="Username" value = '<?php if(isset($_REQUEST['username'])){echo $_REQUEST['username'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyUsername'){
echo "<span class = 'empty-user'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidUserName') {
echo "<span class = 'formaterr-user'>فرمت نام کابری نادرست است*</span>";
}
?>
<label class="pass-label" for="password">رمز عبور</label>
<input type="password" id = "password" name = "password" placeholder = "Password" >
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPass'){
echo "<span class = 'empty-pass'>فیلد نباید خالی باشد *</span>";
}
?>
<div class="checkbox-container">
<input type="checkbox" class = 'checkbox-style' name = 'rules-check'>
<label for="checkbox" class="checkbox-label">من قوانین فروشگاه را کامل مطالعه کرده ام و با آن موافق هستم</label>
<?php if (isset($_REQUEST['rules'])){
echo "<span class = 'rules-error'>قبول قوانین اجباری است و آن را حتما مطالعه کنید *</span>";
}
?>
</div>
<button type="submit" name = "submit" id="submit">ثبت نام</button>
</form>
</div>
<?php
if (isset($_REQUEST['register'])){
echo "<div class = 'register-success'>
<span class = 'register-success-span'>ثبت نام با موفقیت انجام شد</span>
</div>" ;
}
?>
<?php include '../footer.php' ?>
</body>
</html>
MY "register-controller.php" file contains these :
<?php
require "../DB/users-database.php";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit']) && $_POST['rules-check']) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
if (empty($username)){
header("Location: ../page/register.php?error=emptyUsername&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($phone)){
header("Location: ../page/register.php?error=emptyPhone&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($pass)){
header("Location: ../page/register.php?error=emptyPass&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($email)){
header("Location: ../page/register.php?error=emptyEmail&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (!filter_var($email , FILTER_VALIDATE_EMAIL)) {
header("Location: ../page/register.php?error=invalidEmailFormat&username=".$username."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[a-z\d_]{2,20}$/i" , $username)){
header("Location: ../page/register.php?error=invalidUserName&email=".$email."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[0-9]{11}+$/" , $phone)){
header("Location: ../page/register.php?error=invalidPhoneNumber&email=".$username."&phone=".$phone);
exit();
}
else {
$sql = "SELECT username FROM registered WHERE username = ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLcheckUser");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "s" , $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rowcount = mysqli_stmt_num_rows($stmt);
if($rowcount > 0 ) {
header("Location: ../page/register.php?error=UserNameTaken");
exit();
}
else {
$sql = "INSERT INTO registered(email,phone,username,password) VALUES(?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLInsert");
exit();
}
else {
$hased_pass = password_hash($pass , PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt , "ssss" , $email , $phone , $username , $hased_pass);
mysqli_stmt_execute($stmt);
header("Location: ../page/register.php?register=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
elseif (isset($_POST['submit']) && !isset($_POST['rules-check'])) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
header("Location: ../page/register.php?rules=notChecked&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
else {
header("Location: ../page/register.php?access=denied");
exit();
}
?>
You can render the part of the page you prefer depending on your URL parameters by doing
<?php
if ($_GET['success']) { ?>
<-- YOUR HTML SUCCESS CODE -->
<?php } else { ?>
<-- YOUR HTML FORM CODE -->
<?php }
?>
Ajax is the best solution for me (it can be difficult to understand but the code is clean), here an example of Ajax with your situation :
Extras is the ID of all the input in the form
Page is the PHP page to be executed (register-controller.php)
Origin is the ID where you want to put the result, Origin can be null.
(To have something in the return, you have to put an echo in the php file you specified in Page)
static Ajax(origin,Extras,page)
{
var xhr = new XMLHttpRequest();
let formData = new FormData();
for(var element in Extras)
{
if(document.getElementById(element))
{
formData.append(element,document.getElementById(element));
}
else
{
let checkbox = document.getElementsByName(element);
if(checkbox)
{
//Checkbox don't work with an ID so put instead a name
for(let i=0;i<checkbox.length;i++)
{
if(checkbox[i].checked)
{
formdata.append(element+i,"1")
}
else
{
formdata.append(element+i,"0")
}
}
}
}
}
xhr.open('POST',page);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let i= xhr.responseText;
if(origin!=null)
{
if(document.getElementById(origin) && xhr.responseText!="")
// the result document.getElementById(origin).innerHTML=xhr.responseText;
}
finish(i);
}
else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status != 200) {
// error message XHR,
let textError = "Ajax Error : " + xhr.status + ", " + xhr.statusText + ", ";
alert(textError);
}
});
// send
xhr.send(formData);
}
I have a form for password recovery via email. I send input to PHP to do the following:
Validate {three different validation messages)
If passed, Process
Once the response is received, in AJAX, although is not valid, it is considered successful because it has been processed in php.
I need to differentiate between every response so I can display appropriate alert messages
if field input is empty, I want to show it in alert-info message box
if field input is noa t valid email, I want to show it in alert-warning message box
if field input is not found the in server, I want to show it in alert-danger message box
if successful, I want to show it in alert-success
$(function() {
// Get FORM ID ///////////////////////////////////////////
var form = $('#RecoveryForm');
// Get MESSAGE DIV ID ///////////////////////////////////////////
var formMessages = $('#formresults');
$(form).submit(function(e) {
$( "#submit" ).prop( "disabled", false );
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
// Get FORM ID ///////////////////////////////////////////
document.getElementById("RecoveryForm").reset();
//$('#reset-button').click();
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
$("#submit").removeAttr("disabled");
});
});
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="formresults"></div>
<form id="RecoveryForm" method="post" action="exa.php">
<table align="center">
<tr><td><div class="input-append"><input type="text" name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" /><span class="add-on"><li class="icon-envelope"></li></span></div></td></tr>
</table>
<input type="hidden" name="token" value="<?=Token::generate();?>" />
<center><input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" /></center>
</form>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
<!---------------------------------------------------------------->
<?php include 'footer.php'; ?>
</body>
</html>
PHP Code >>
<?php
header('Content-type: application/json');
require 'Access.php'; // Get Access
//response array with status code and message
$response_array = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["email"];
if ( empty($email) ) {
$response_array['status'] = 'info';
$response_array['message'] = 'No Input';
echo json_encode($response_array);
exit;
}
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
$response_array['status'] = 'warning';
$response_array['message'] = 'Not Valid Email';
echo json_encode($response_array);
exit;
}
if (#mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
$response_array['status'] = 'danger';
$response_array['message'] = 'Account Not Found';
echo json_encode($response_array);
exit;
}
$row_user = #mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
$password = $row_user['pass'];
$to = $row_user['email'];
$subject = "Your Recovered Password";
$message = "Please use this password to login: " . $password;
$headers = "From : XXX#hotmail.com";
// Send the email.
if (mail($to, $subject, $message, $headers)) {
$response_array['status'] = 'Success';
$response_array['message'] = 'Email Sent';
echo json_encode($response_array);
} else {
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
}
} else {
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
}
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
?>
First of all we start validation from the html of cause this can be hampered and manipulated by the user but still a good way to start.
first we add the required attribute to your input fields in html and change the input types to match the data types your expecting eg: input type="email" hiding an input does not prevent it form being tampered with, best to add the Readonly attribute also.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="formresults"></div>
<form id="RecoveryForm" method="post" action="exa.php">
<table align="center">
<tr>
<td>
<div class="input-append">
<input type="email" Required name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" />
<span class="add-on"><li class="icon-envelope"></li></span>
<p id="mailerror"></p> <!-- This Segment Displays The Validation Rule For Email -->
</div>
</td>
</tr>
</table>
<input type="hidden" Readonly name="token" value="<?=Token::generate();?>" />
<center>
<input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" />
</center>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
</form>
</body>
</html>
Second of all you are using jquery although this much much more easy to use i will suggest you start with java script validation, using the onsubmit attribute to catch the form and begin validation. you will be better understand what exactly is going on as a beginner rather than jquery.
<script>
$(function() {
/*Get FORM ID*/
var form = $('#RecoveryForm');
/*Get MESSAGE DIV ID */
var formMessages = $('#formresults');
/*Email Validation*/
var email_regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $('#email').val();
if (!email.match(email_regex) || email.length == 0) {
$('#mailerror').text("* Please enter a valid email address *");
$("#email").focus();
return false;
}
else if (email.match(email_regex) && email.length >= 5){
$(form).submit(function(e) {
$( "#submit" ).prop( "disabled", false );
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
if (response.status=='Success'){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response.message);
}
else if (response.status=='warning'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
else if (response.status=='danger'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
else if (response.status=='info'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
/*Get FORM ID */
document.getElementById("RecoveryForm").reset();
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
$("#submit").removeAttr("disabled");
});
}
});
</script>
Third of all your PHP could have been better written but it works fine presumably :( so we leave that for now.
report different response with php validation
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><button type="button" class="close" data-dismiss="alert">×</button><d style="font-size:11px; ">' + messageText + '</d></div>';
(formMessages).html(alertBox);
For every PHP statement add:
$responseArray = array('type' => 'alert-warning', 'message' => '<b>Alert!</b>There is not enough credit');
Then send response json encoded
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray); header('Content-Type: application/json'); echo $encoded; } else { echo $responseArray['message']; }
Im facing a problem Notice: Undefined index: company in C:\xampp\htdocs\new_exp\login.php on line 4
Errors
At here i have 3 database. exp, new_1 and new_2. In exp database have company table which contain id, company_name, and database_name attributes.
There are two database connection that i use which are dbconnection_main.php and dbconnection.php. dbconnection_main.php i used to call ada database which storing company_name and database_name table. Once user selected option of company_name when login in same time it will call the database_name.
The error occur when i login.
This is my index.php
<?php
session_start();
error_reporting(-1);
// Cek Active Link
function ActiveClass($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="active"';
}
//check already login
if (!isset($_SESSION['UserId'])) {
header ('Location: login');
exit;
}
if ($_SESSION['level'] == 'APPROVAL'){
header ('Location: login');
exit;
}
//Link to page
if (isset($_GET['page']) && $_GET['page'] == 'ManageCategory') {
$page = "ManageExpenseCategory";
} else {
$page = 'dashboard';
}
//get global notification
include('includes/global.php');
//Get Header
include('includes/header.php');
//set global message notification
$msgBox ="";
if (file_exists('pages/'.$page.'.php')) {
// Load the Page
include('pages/'.$page.'.php');
} else {
// Else Display an Error
echo '
<div class="wrapper">
<h3>Err</h3>
<div class="alertMsg default">
<i class="icon-warning-sign"></i> The page "'.$page.'" could not be found.
</div>
</div>
';
}
include('includes/footer.php');
?>
So here is my login.php
<?php
session_start();
error_reporting(-1);
$_SESSION['db_company_name'] = $_POST['company'];
$msgBox = '';
//include notification page
include ('includes/notification.php');
//Include db Page
require_once ('includes/dbconnection.php');
//Include Function page
include ('includes/Functions.php');
//User Login
if(isset($_POST['login']))
{
$username = $mysqli->real_escape_string($_POST['email']);
$Password = encryptIt($_POST['password']);
if ($stmt = $mysqli->prepare("SELECT UserId, company_id, FirstName, LastName, Email, Password, level, admin_access, Currency from user WHERE Email = ? AND Password = ? "))
{
$stmt->bind_param("ss", $username, $Password);
$stmt->execute();
$stmt->bind_result($UserId_, $CompanyId_, $FirstName_, $LastName_, $Email_, $Password_, $Level_, $Admin_access_, $Currency_);
$stmt->store_result();
$stmt->fetch();
if ($num_of_rows = $stmt->num_rows >= 1)
{
session_start();
$_SESSION['UserId'] = $UserId_;
$_SESSION['FirstName'] = $FirstName_;
$_SESSION['LastName'] = $LastName_;
$_SESSION['level'] = $Level_;
$_SESSION['admin_access'] = $Admin_access_;
$_SESSION['Currency'] = $Currency_;
$_SESSION['company_id'] = $CompanyId_;
$compId = $_SESSION['company_id'];
$UserIds = $_SESSION['UserId'];
$company_q = mysqli_query($mysqli, "SELECT * FROM company_setting where company_id = '".$compId."'");
$company = mysqli_fetch_assoc($company_q);
$_SESSION['company_name'] = $company['company_name'];
if ($_SESSION['level'] === 'STAFF'){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index">';
}
else
{
$msgBox = alertBox($LoginError);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<div class="panel-body">
<?php if ($msgBox) {
echo $msgBox;
} ?>
<form class="form-horizontal m-t-20" method="post" action="" role="form">
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" onBlur="checkcompany(this.value)" type="email" required placeholder="<?php echo $Emails; ?>" name="email" id="email" autofocus>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="password" value="" required placeholder="<?php echo $Passwords; ?>">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<span id="result"><select name="company" id="company" class="form-control" required><option>company</option></select></span>
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" name="login" class="btn btn-primary btn-block text-uppercase waves-effect waves-light"><?php echo $SignIn; ?></button>
</div>
</div>
</form>
</div>
<script>
function checkcompany(v)
{
//alert(v);
var dataString = 'email='+v;
//document.getElementById('loginbtn').style.display = "none";
$.ajax({
type: "POST",
url: "checkaccount.php",
data: dataString,
cache: true,
success: function (result){
$("#result").html(result);
//document.getElementById('loginbtn').style.display = "block";
}
})
}
</script>
This is my checkaccount.php
<?php
error_reporting(-1);
session_start();
include("includes/dbconnection_main.php");
$email = $_POST['email'];
?>
<select name="company" id="company" class="form-control" required>
<option value="">----------------</option>
<?php
$company_q = mysqli_query($mysqli, "SELECT * FROM company");
while($company = mysqli_fetch_assoc($company_q))
{
//connect to sub database
$conn_hostname = "localhost";
$conn_database = $company['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqlii = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
$check_q = mysqli_query($mysqlii, "SELECT * FROM user WHERE Email = '".$email."' AND status = 'ACTIVE' AND password != ''");
$check = mysqli_num_rows($check_q);
if (!$check) {
printf("Error: %s\n", mysqli_error($mysqlii));
exit();
}
if($check >= 1)
{
?>
<option value="<?php echo $company['company_name']; ?>"><?php echo strtoupper($company['company_name']); ?></option>
<?php
}
mysqli_close($mysqlii);
}
?>
</select>
SO this is my dbconnection_main.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
?>
And This is my dbconnection.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
if(!isset($_SESSION))
{
session_start();
}
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
$mysqlie = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$get_database_q = mysqli_query($mysqlie, "SELECT * FROM company WHERE company_name = '".$company_name."'") or trigger_error(mysqli_error($mysqlie),E_USER_ERROR);
$get_database = mysqli_fetch_assoc($get_database_q);
if (!$get_database) {
printf("Errors: %s\n", mysqli_error($mysqlie));
exit();
}
$conn_hostname = "localhost";
$conn_database = $get_database['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqli = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
?>
I cannot detect the error since it only give me such general error prompt out. I think it might be related with dbconnection.php at this part which related with $_session..
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
So I am using ajax and php to 'create a post' which allows you to upload images along with text. Currently I have the php working to check if the post has any content and if it has an image, and validating everything. However the problem is when I get a response I am prepending it to the post feed, but this makes it so that when there is an error it also prepends it to the feed. What I would like to do is append the errors to a separate div called errors.
Here is my php (I'm just starting with php and if something is wrong or could have been done easier with less work, please let me know.)
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if (!getimagesize($_FILES[$image]['tmp_name'])) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
?>
<article class="post">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username']; ?>
</a>
</div>
<img src="users/user_<?php echo $rowuser['user_id'] ?>/posts/<?php echo $row['image']; ?>" alt="">
<div class="post-body">
<div class="post-options">
<a class="likes" href="">156 likes</a>
</div>
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }else{ ?>
<article class="post no-img">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username'] ?>
</a>
</div>
<div class="post-body">
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<div class="post-options">
<a class="likes" href="">1 like</a>
</div>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }
}else{
echo 'There was a database error';
}
die();
Here is my ajax call
$.ajax({
type: "post",
url: "includes/create-post.php",
data: new FormData(this),
processData: false,
contentType: false,
error: function (response) {
console.log(response);
},
success: function (response) {
$('section.feed').prepend(response);
$('article.post p').each(function () {
$(this).html(linkHashtags($(this).html()));
});
$('article.post p').each(function () {
$(this).html(linkatsymbols($(this).html()));
});
revealPosts();
}
});
For the die() you can simply put the statement die out of foreach like this:
if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
.
.
.
.
.
.
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}
else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
But since you want to display the errors in some other element, you need a way to check whether the output you are receiving is an error. So try replacing your code with this:
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}
else {
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
And in your AJAX success call do something like this:
success: function (response) {
var obj = JSON.parse(response);
var errorCode = obj.responseCode;
var errorSet = obj.items;
if(errorCode == 0) {
$.each(errorSet, function(i, v) {
console.log('<li>'+v+'</li>');
}
}
//Your rest of the code
BTW, its better if you separate your code from your design.
I have a simple login form in which I have passed the values through AJAX call. The problem is when I enter wrong email or password for first time, It displays me the error message. 2nd time if I enter something wrong it does not show the error. Where am I doing wrong any suggestions/help please.
Form
<?php
if (isset($_SESSION['login_email']) && !empty($_SESSION['login_email'])) {
//header('Location:profile.php');
?>
<script> location.replace("profile.php"); </script>
<?php
} else {
?>
<div class="login_form">
<h1 class="login_heading">Login</h1>
<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
<form method="post" action="">
<label >Email</label>
<input class="inputs_login" type="email" name="email" id="email" placeholder="email" >
<label>Password</label>
<input class="inputs_login" type="password" name="password" id="password" placeholder="password"><br>
<input type="button" name="login_submit" id="login_submit" value="login">
</form>
</div>
</div>
<?php
}
?>
Ajax
<script>
$(document).ready(function() {
$('#login_submit').click(function(e){
//e.preventDefault();
var email = $("#email").val(),
password = $("#password").val();
var proceed = true;
if(proceed){
post_data= { 'Email': email, 'Password': password};
$.post('login_index.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output=$('.alert-error').html(response.text);
}else{
location.href="profile.php";
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
php
<?php
include "db/db.php";
session_start();
if ($_POST) {
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if (isset($_POST['Email']) && isset($_POST['Password'])) {
$email = filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd = filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query = mysqli_query($con, "select * from customers where email='$email' and password='$pwd'");
$count = mysqli_num_rows($query);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
if ($row) {
$_SESSION['login_email'] = $row['email'];
$output = json_encode(array(
'type' => 'message',
'text' => 'Hi ' . $email . ' You are successfully login'
));
die($output);
} else {
$output = json_encode(array(
'type' => 'error',
'text' => 'Could not Login! Please check your email/password OR REGISTER FREE ACCOUNT .'
));
die($output);
}
}
}
?>