Javascript and php copy button - javascript

I am trying to create a Button so the user can copy the $filename the code works for the first one but not for the rest I understand that this is because I would probably need to array the js-copyfilename and js-copyfilenamebtn classes so each one is different but then I know very little about JavaScript so wouldn't know where to start
Thanks in advance
<p>Current Images Inside Gallery
<br />
<?php foreach($rows as $row): ?>
<div class="t">
<table class="table2">
<tr>
<td class="table2"><?php echo $row["id"]; ?></td>
</tr>
<tr>
<td><img src="images/<?php echo $row["photo"] ; ?>" alt="" width="130" height="130" /></td>
</tr>
<tr>
<td><textarea class="js-copyfilename" readonly="readonly" ><?php echo $row["photo"];?></textarea>
<button class="js-copyfilenamebtn">Copy Filname</button>
</td>
</tr>
</table>
</div>
<?php endforeach;?>
</div>
<script type="text/javascript">
var copyfilenameBtn = document.querySelector('.js-copyfilenamebtn');
copyfilenameBtn.addEventListener('click', function(event) {
var copyfilename = document.querySelector('.js-copyfilename');
copyfilename.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
</script>​

For anybody trying to do something similar I done it like so... This code selects all rows in db, puts them into table, and then creates a copy filename button for each of them and copies the one you click into the filename field once you enter the id and click submit the delete form it will delete that image from the database and directory + a few other validation checks
function ClipBoard(obj) {
var filename = document.getElementById("filename");
filename.innerText = obj.innerText;
Copied = filename.createTextRange();
Copied.execCommand("Copy");
}
#charset "utf-8";
/* CSS Document */
#wrap
{
height:800px;
text-align:center;
}
.table1 {
text-align:center;
font-weight: bold;
width: 130px;
font-size:14px;
}
.table2 {
float:left;
text-align:center;
font-weight: bold;
width: 130px;
border: 1px solid #000;
font-size:14px;
}
.t {
width:140px;
display:inline-block;
margin:0 auto;
}
.js-copyfilename {
text-align:center;
font-weight: bold;
width: 128px;
height:16px;
border:1px solid #000;
font-size:14px;
overflow:hidden;
}
<?php
// Include Databse
include "common.php";
// validation errors
$error = array();
// Check if form has been submitted
if (isset ($_POST['delete']))
{
// get the filename & id. See php.net/basename for more info
$filename = basename($_POST['filename']);
$id =($_POST['id']);
// get file extension, see php.net/pathinfo for more info
$ext = pathinfo($_POST['filename'], PATHINFO_EXTENSION);
// allowed file extensions
$allowedExtensions = array('jpeg','jpg','gif','png','bmp');
// Check filename is not empty
if(empty($filename))
{
$error[] = "Please enter a Filename";
}
// Check valid file extension used
else if(!in_array($ext, $allowedExtensions))
{
$error[] = "Please check Filename";
}
// Check ID is not empty
if(empty($_POST['id']))
{
$error[] = "Please enter a ID";
}
else if(is_numeric($id))
{
// Check ID exists in database
$query = "SELECT id FROM `test` WHERE `id` = :id" ;
$stmt = $db->prepare($query);
$stmt->bindParam(":id", $id);
$stmt->execute();
if(!$stmt->rowCount() == 1)
{
$error[] = "Please check ID";
}
}
else {
$error[] = "ID is not numeric";
}
// delete file from database if there are no errors
if (empty($error))
{
// path to the image
$file_to_delete = 'images/' . $filename;
// Checks the file exists and that is a valid image
if(file_exists($file_to_delete) && getimagesize($file_to_delete))
{
// Delete File From Directory
unlink($file_to_delete);
}
else
{
$error[] = "File not found please check Filename";
}
if (empty($error))
{
// Run Query To Delete File Information From Database
try
{
$query = "DELETE FROM `test` WHERE `id` = :id";
$stmt = $db->prepare($query);
$stmt->execute(array('id' => intval($_POST['id'])));
}
catch(PDOException $ex)
{
die("Failed to run query: Please report issue to admin");
}
$status = "File Deleted";
}
}
}
// Run Query To Show The Current Data In Database
try
{
$query = "SELECT id,photo FROM test ORDER BY id";
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: Please report issue to admin");
}
$rows = $stmt->fetchAll();
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<link href="css/delete.css" rel="stylesheet" type="text/css" />
<script src="copy.js"></script>
</head>
<body>
<div id="wrap">
<form action="delete.php" method="post" enctype="multipart/form-data">
Please enter the Filename and ID of the image you wish to delete
<table width="284" align="center">
<tr>
<td width="144" class="table1">Filename</td>
<td width="128" class="table1">ID </td>
</tr>
<tr>
<td class="table1"><input name="filename" id="filename" type="text" value="<?php echo $filename; ?>" /></td>
<td class="table1"><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="4" /></td>
</tr>
</table>
<p>
<?php
// Show validation errros here
if(!empty($error)):
echo implode('<br />', $error);
echo $status;
endif;
?>
<br />
<input type="submit" value="Delete Selected Image" name="delete" />
</p>
</form>
<p>Current Images Inside Gallery
<br />
<?php
foreach($rows as $row):
$i = $row["photo"];
?>
<div class="t">
<table class="table2">
<tr>
<td class="table2"><?php echo $row["id"]; ?></td>
</tr>
<tr>
<td><img src="images/<?php echo $row["photo"] ; ?>" alt="" width="130" height="130" /></td>
</tr>
<tr>
<td><?php print '<textarea class="js-copyfilename" name="copytext'.$i.'" id="copytext'.$i.'">'.$i.'</textarea>
<input type="button" onclick="ClipBoard(document.getElementById(\'copytext'.$i.'\'));" value="Copy Filename">
'; ?>
</td>
</tr>
</table>
</div>
<?php endforeach;?>
</div>
</body>
</html>
COMMON.PHP
<?php
// These variables define the connection information for your MySQL database
$username = "";
$password = "";
$host = "";
$dbname = "";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like ¢ or €, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.

Related

How do I display the HTML GET request data on the same HTML page, using a separate PHP file to fetch it?

I'm trying to get data from a MySQL database, that is being selected from a dropdown in an HTML file, and have the data display on the same HTML page that it is being selected from. I already have the HTML and PHP working to retrieve the data and display it, but it is not displaying on the same page that the user requests it from, it is displaying on the PHP page.
Here is the HTML code for get_project_form.html :
<html>
<head>
<title>Get Project Form</title>
<!--Link this html page to the project_style.css page-->
<link rel="stylesheet" type="text/css" href="project_style.css">
</head>
<body>
<div class="container">
<form action="get_project_action.php" autocomplete="off" method="get">
<label for="Query Selections">Query Selections : (You can only select
all data from "Projects"
for now):</label>
<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
<option value="Projects">Projects</option>
</select><br />
<input type="submit" value="Submit"><br />
</div>
</body>
</html>
After you make the selection and click submit the data appears on a page with the URL,
http://localhost:8015/get_project_action.php?queries=Projects
Here is the code for the php file get_project_action.php :
<?php
echo "<table style='border: solid 1px black;'>";
class TableRows extends RecursiveIteratorIterator
{
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 150px; border: 1px solid black;'>" .
parent::current() . "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pmo";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $_GET["queries"];
$stmt = $conn->prepare("SELECT * FROM $query");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as
$k => $v) {
echo $v;
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
I'd like to keep the HTML and PHP separate if possible. But from what I'm reading I'm guessing that isn't possible. I'm hearing that its best to keep the logic in a separate PHP file but that its best to put the rest of the PHP that does the displaying in the HTML file and change the .html file to a .php instead. But I was hoping there is a way to have the data display in the get_project_form.html page below the form somewhere without combining any of the PHP inside the get_project_form.html file and changing it to a .php. If this is possible, please show me how. If not, please feel free to show me how to do whatever is considered good practice for displaying the data on a web page. Any help will be highly appreciated!
suppose in php file you are using $dropdownData array variable to store data from db.
//PHP file
<?php
//query to fetch data from db.
$dropdownData;
$this->view('get_project_form.html',$dropdownData);
?>
//Then use this array variable $dropdownData in ur HTML file with "for loop" to display
//HTML file
//you can also validate the $dropdownData if it's not empty; otherwise php will give error.
<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
<? foreach ($dropdownData as $val => $text) { ?>
<option value="<? echo $val; ?>" > <? echo $text;?> </option>
<? } ?>
</select>

php showing logout button only if logged in

I am writing the code for a simple website where users log in and out and some other basic functions. I would like it to be so when anyone logs in, a logout button is shown on all the pages they visit, and hidden if they are not logged it. I am still new and cannot figure out what is wrong. The logout button appears as soon as i initially click the login button, but when i navigate to other pages the button disappears from my menu.
menu.php
$currentfile = basename($_SERVER['PHP_SELF']);
if($currentfile = basename($_SERVER['PHP_SELF'])){
if (isset($_SESSION['ID'])) {
echo "Home
See Reviews
Write a Review
Search
<a href='logoutconfirmation.php'>Logout</a>
<hr />";
}else{
echo "Home
See Reviews
Write a Review
Search
<hr />";
}
} ?>
index.php
<?php
include "header.inc.php";
$pagetitle= "Login Form";
$showform =1;
$errormsg =0;
$errorusername = $errorpassword = "";
$inputdate = time();
//FIRST CHECK TO SEE IF THE USER IS LOGGED IN
if(isset($_SESSION['ID']))
{
echo "<p class='error'> You are already logged in. </p>";
include_once "footer.inc.php";
exit();
}
if(isset ($_POST['submit'])) {
/*************************************************************
* ALL FIELDS- STORE USER DATA; SANITIZE USER-ENTERED DATA
*************************************************************/
$formfield['username'] = trim($_POST['username']);
$formfield['password'] = trim($_POST['password']);
if (empty($formfield['username'])) {
$errorusername = "The username is required.";
$errormsg = 1;
}
if (empty($formfield['password'])) {
$errorpassword = "The password is required.";
$errormsg = 1;
}
if ($errormsg != 0) {
echo "<p class='error'> THERE ARE ERRORS!</p>";
} else {
//get the user data from the database
try {
$user = "SELECT * FROM Users WHERE username =:username";
$stmt = $pdo->prepare($user);
$stmt->bindValue(':username', $formfield['username']);
$stmt->execute();
$row = $stmt->fetch();
$countuser = $stmt->rowCount();
// if query okay, see if there is a result
if ($countuser < 1) {
echo "<p class='error'> *This user cannot be found in the
database* </p>";
} else {
if (password_verify($formfield['password'], $row['password'])) {
$_SESSION['ID'] = $row['ID'];
$showform = 0;
header("LocationL confirm.php?state=2");
echo "<p> Thank you for logging in! </p>";
} else {
echo "<p class='error'> The username and password
combinations you entered are not correct. Please try again! </p>";
}
}//username exists
} catch (PDOException $e) {
echo 'ERROR fetching users: ' . $e->getMessage();
exit();
}
}
}
if($showform == 1) {
?>
<p class="homemsg">Welcome to the Movie Review Hub! Feel free to look
around or sign in to write your own review.</p>
<form name="login" id="login" method="post" action="index.php">
<table class="center">
<tr>
<th><label for="username">Username: </label></th>
<td><input name="username" id="username" type="text" placeholder="Required Username"
}?><span class="error" <?php if (isset($errorusername)) {
echo $errorusername;
} ?></span></td>
</tr>
<tr>
<th><label for="password">Password: </label></th>
<td><input name="password" id="password" type="password" placeholder="Required Password"
}?><span class="error"> <?php if (isset($errorpassword)) {
echo $errorpassword;
} ?></span></td>
<tr>
<th><label for="submit">Submit: </label></th>
<td><input type="submit" name="submit" id="submit" value="submit"/></td>
</tr>
</table>
<p><a href=index.php>Register.</a></p>
<?php
include_once "footer.inc.php";
}
?>
Like I said i would like the logout button to be show on all of the pages if someone logs in from the index page, the menu is included in all of my files
The logout button initially shows when i press the login button, but when i refresh the page or navigate to another page it goes away.
Like #CBroe mention, try add session_start at start of every page.
Better create config file, put it there and include everywhere.

AJAX comment system, ajax not working

I am making a comment system for my blog that I am creating and currently I have two problems with it. The form appears under every post. But only works on the top post. The rest of the forms simply don't work.
The another problem I have is that I'm using ajax and the form does add the record to SQL but I still have to refresh my page for it to show. I want it to show automatically straight away after it is added.
tl:dr
Two problems:
The only form that works is the first one under the first post, the rest simply don't work
Ajax doesn't automatically show the comments, need to refresh to seem them
Code:
JQuery
function post()
{
var comment = document.getElementById("comment").value;
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var post_id = document.getElementById("post_id").value;
if(comment && name && mail)
{
$.ajax
({
type: 'post',
url: 'php/comment.php',
data:
{
user_comm:comment,
user_name:name,
user_mail:mail,
post_id:post_id,
},
success: function (response)
{
document.getElementById("comments").innerHTML=response+document.getElementById("comments").innerHTML;
document.getElementById("comment").value="";
document.getElementById("name").value="";
document.getElementById("mail").value="";
}
});
}
return false;
}
Index.php
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id_post = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
echo " <!-- Blog Post Content Column -->
<h1> " . $row['post_title'] . " </h1><p class='lead'>
by <a href='#'>Matt</a></p> <hr>
<p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
<img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
<p class='lead'>" . $row['post_first'] . "</p>
<p>" . $row['post_second'] . "</p> <hr>";
?>
<!-- Comments Form -->
<div class='well'>
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method='post' onsubmit="return post();">
<input type='hidden' id='post_id'name='post_id' value='<?php echo $id_post; ?>'>
<div class='form-group'>
<input type="text" id="name" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type='text' id='comment' name='comment' class="form-control" rows='3'></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<?php
$resultcomments = mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC") or die(mysql_error());
while($affcom = mysql_fetch_assoc($resultcomments)){
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<!-- Posted Comments -->
<div id='comments'class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
}
?>
</div>
comment.php
include_once('../../acp/db/db.php');
$link = mysql_connect($dbhost, $dbuser, $dbpassword, $dbname);
mysql_select_db($dbname);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail']))
{
$comment=$_POST['user_comm'];
$name=$_POST['user_name'];
$mail=$_POST['user_mail'];
$post_id=$_POST['post_id'];
$insert=mysql_query("INSERT INTO comment (name,mail,comment,post_id) VALUES ('$name', '$mail', '$comment', '$post_id')");
$select=mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC");
if($row=mysql_fetch_array($select))
{
$name=$row['name'];
$comment=$row['comment'];
$date=$row['date'];
?>
<div class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
exit;
}
?>
This is the first time I am playing around with AJAX :) so be easy on me Any help will be appreciated.
I tested all your code. It's working now. I commented it overall, so search after "NB" (lat. for "Nota bene") in codes, in order to see were I made relevant changes. I'll describe here some problems with it and I'll also give you some recommendations - if I may. At last I'll insert the three corrected pages.
Problems:
One big problem was, that you were using the $id_post variable in
the SELECT sql statement (in comment.php), which does not exist
in comment.php code.
Other problem: DOM elements had same ids. The DOM elements inside
loop-forms must have unique id attributes. You must always have
unique id attributes in html elements. Give them the form
id="<early-id><post_id>" for example.
There were also other problems in more places. I commented overall,
so you'll have to read my codes.
Recommendations:
Use mysqli_ instead of mysql_ functions, because mysql
extension were completely removed from PHP >= 7.0.
Use exception handling, especially when dealing with db access.
Don't write HTML code from inside php. Alternate php with html if you
wish, but don't do echo "<div class=...></div>" for example. This
is actually very important if you use an IDE which can format your
html code. If this code is inside php, you have no chance for this
beautifying process. therefore you can miss important html-tags
without knowing it, because your IDE didn't showed you where tags are
really missing in page.
In html tags: use same name as id. Example: id=mail<?php echo
$post_id; ?>, name=mail<?php echo $post_id; ?>. Exception: radio
buttons, checkboxes and all tags which can form a group. Then, each
tag would have a unique id, but all of them would receive the same
name.
Use '' overall and "" inside them. Maintain this "standard", you'll see it's a lot better than the inverse.
Corrected pages:
Index.php:
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
<!-- NB: Added my scripts for testing -->
<link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
<script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
if (!$result) {
throw new Exception('The query could not be executed!');
}
while ($row = mysqli_fetch_array($result)) {
// NB: Unified $post_id name overall (instead of $id_post).
$post_id = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
?>
<!-- Blog Post Content Column -->
<!--
NB: Extracted html code from php and added here, where it should be.
-->
<h1>
<?php echo $post_title; ?>
</h1>
<p class="lead">
by Matt
</p>
<hr/>
<p>
<span class="glyphicon glyphicon-time">
<?php echo $post_date; ?>
</span>
</p>
<img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
<hr/>
<p class="lead">
<?php echo $post_first; ?>
</p>
<p>
<?php echo $post_second; ?>
</p>
<hr/>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
<!--
NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute!
So: transfered post_id value to post() function as argument. See js too.
-->
<!--
NB: Added post_id to the "id" attributes. See js too.
-->
<div class="form-group">
<input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<!--
NB: Added new "comments" outer-container in order to append
new comment to it and added post_id value into its "id" attribute.
See the js too.
-->
<div id="comments<?php echo $post_id; ?>" class="comments-container">
<?php
$resultComments = mysqli_query($con, 'SELECT * FROM `comment` WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
if (!$resultComments) {
throw new Exception('The query could not be executed!');
}
while ($affcom = mysqli_fetch_assoc($resultComments)) {
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<!-- Posted Comments -->
<!--
NB: deleted id attribute "comments", because I added an outer
container to hold the insert results, e.g. the div
with the class "comments-container".
-->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="<?php echo $grav_url; ?>" >
</a>
<div class="media-body">
<?php echo $name; ?>
<h4 class="media-heading">
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
<?php
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
comment.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
</head>
<body>
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
$comment = $_POST['user_comm'];
$name = $_POST['user_name'];
$mail = $_POST['user_mail'];
$post_id = $_POST['post_id'];
// NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
// Use UNIX timestamps for dates, so that you make good date calculations.
$date = date("Y-m-d");
// NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
$insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
if (!$insert) {
throw new Exception('The query could not be executed!');
}
// NB: Replaced $id_post with $post_id.
$select = mysqli_query($con, "SELECT * FROM `comment` WHERE post_id = '$post_id' ORDER BY `date` DESC");
if (!$select) {
throw new Exception('The query could not be executed!');
}
if ($row = mysqli_fetch_array($select)) {
$name = $row['name'];
// NB: Added email, because it wasn't provided.
$email = $row['mail'];
$comment = $row['comment'];
$date = $row['date'];
// NB: It wasn't provided, so I added the same value as in index.php.
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<div class="media">
<a class='pull-left' href='#'>
<!--
NB: Where is your $grav_url value?! I added one of mine for testing.
-->
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'>
<?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
// NB: Don't use exit(). Let the code flow further, because
// you maybe want to close the db connection!
// exit();
}
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
</body>
</html>
Javascript file:
// NB: Added post_id as parameter. See form too.
function post(post_id) {
// NB: Added post_id value to the "id" attributes. See form too.
var comment = document.getElementById("comment" + post_id).value;
var name = document.getElementById("name" + post_id).value;
var mail = document.getElementById("mail" + post_id).value;
if (comment && name && mail) {
$.ajax({
type: 'post',
url: 'php/comment.php',
data: {
user_comm: comment,
user_name: name,
user_mail: mail,
post_id: post_id
},
success: function (response) {
// NB: Comments-post_id is now an outer container. See form.
// NB: Added post_id value to the "id" attributes. See form too.
document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
document.getElementById("comment" + post_id).value = "";
document.getElementById("name" + post_id).value = "";
document.getElementById("mail" + post_id).value = "";
}
});
}
return false;
}
// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
// var comment = $('#comment' + post_id);
// var name = $('#name' + post_id);
// var mail = $('#mail' + post_id);
//
// if (comment && name && mail) {
// var ajax = $.ajax({
// method: 'POST',
// dataType: 'html',
// url: 'php/comment.php',
// data: {
// user_comm: comment.val(),
// user_name: name.val(),
// user_mail: mail.val(),
// post_id: post_id
// }
// });
// ajax.done(function (data, textStatus, jqXHR) {
// var comments = $("#comments" + post_id);
//
// // NB: I'm not sure, not tested, too tired :-) Please recherche.
// comments.html(data + comments.html());
//
// comment.val('');
// name.val('');
// mail.val('');
// });
// ajax.fail(function (jqXHR, textStatus, errorThrown) {
// // Show error in a customized messages div, for example.
// $('#flashMessage').val(textStatus + '<br />' + errorThrown);
// });
// ajax.always(function (data, textStatus, jqXHR) {
// //...
// });
// }
//
// return false;
//}
// ******************************************************************************
Good luck.
Your parent loop is generating several comments form and they all have the same id. Ids are supposed to be unique for the whole document. refer this. Perhaps this is causing other comment forms not to work except the first one.
Your second problem is not an issue. It is general behavior of how server works. When you are using ajax, it is sending data to the server which stores it in the database. Server's job is done. It cannot send the data back to the page and update the page content without refreshing the page. You can initiate another ajax call after posting to server in order to refresh the content of the page.
And though it is not related to the question. Try to be consistent with your use of single quotes and double quotes. You shouldn't randomly choose them. Decide on one and use them consistently. And yes do try to learn PDO or mysqli. I will suggest PDO.

Alert the value in java-script which is queried from Database without using Ajax

i am working on a mini project to display value queried from database based on the check box selected.
i have come across many post : it can be done using ajax/jquery.
i donot know how to use ajax.
pl help me i am stuck at final Alert window output.
Here is my main test.php
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>--</title>
<script>
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[type="checkbox"]:checked')) {
//alert("Success! (form would be submitted here)");
var $temp = <?php include 'alert.php';?>
//alert("Success! (form would be submitted here)");
alert($temp)
document.frmUser.action = "test.php";
document.frmUser.submit();
} else {
alert("Pl select checkbox which You wish to Update ");
}
}
</script>
</head>
<body >
<h1 style="text-align:center;"></h1>
<?php
// php populate html table from mysql database
$conn = mysqli_connect("localhost","root","11111111");
mysqli_select_db($conn, "test");
$result = mysqli_query($conn,"SELECT * FROM inputs ORDER BY userId DESC");
?>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<div style="width:1200px;">
<table style="text-align:center;"border="0" cellpadding="10" cellspacing="1" width="1200" class="tblListForm" align="center">
<tr class="listheader">
<td></td>
<td>SN</td>
<th>Domain</th>
<th>department</th>
<th></th>
</tr>
<?php
$i=0;
$j=1;
while($row = mysqli_fetch_array($result)) {
if($i%2==0){
$classname="evenRow";
} else {
$classname="oddRow";
}
?>
<tr class="<?php if(isset($classname)) {
echo $classname;
}?>">
<td><input type="checkbox" name="users[]" value="<?php echo $row["userId"]; ?>" ></td>
<td><?php echo $row["userId"]; ?></td>
<td><?php echo $row["department"]; ?></td>
<th colspan="4"><input type="button" name="update" class="button" value="Apply" onClick="checkAddress(this);" /></th></tr>
<?php
$i++;
$j=$i+1;
}
$conn->close();
?>
</table>
</div>
</form>
</div>
</body>
</html>
Below is my alert.php
<?php
$servername = "localhost";
$username = "root";
$password = "11111111";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$rowCount = count($_POST['users']);
//echo "The rowcount is ".$rowCount."";
$queried_name;
for($i=0;$i<$rowCount;$i++) {
$num_var= " ";
$num_var = mysqli_real_escape_string($conn,$_POST['users'][$i]);
//echo "The numvar is ".$num_var."";
$result = mysqli_query($conn, "SELECT * FROM inputs WHERE userId='".$num_var."'");
if (!$result) {
echo 'MySQL Error: ' . mysqli_error($conn);
exit;
}
while($row[$i]= mysqli_fetch_array($result)) {
$queried_name = $row[$i]['department'];
return $queried_name;
echo 'alert("Please Use below department.' .$queried_name.'")';
}}}
$conn->close();
?>
If you are using jQuery, you can make use of their inbuilt ajax function. If you are limited to "vanilla" javascript, below is the function I normally use for AJAX calls:
function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
var xmlHttpRequest = new XMLHttpRequest();
var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
xmlHttpRequest.open(method, url, async);
xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
xmlHttpRequest.send(param);
if(!async) { callback(xmlHttpRequest); }
}
Usage example:
ajaxQuery('alert.php', 'GET', null, true, function(r) {
alert(r.responseText);
}, function() { alert('Something went wrong.'); });
Naturally, if alert.php performs any complex tasks, it will have to take parameters, and you then could refer to alert.php?parameter0=something&parameter1=something instead of just alert.php.
I would recommend doing something a bit more simple at this stage, as you are confusing php with javascript, and you seem to not quite understand what exactly an include statement does in a php file. It doesn't return the output of the script - what it does is kind of equivalent to echoing the whole php file into another! You were assigning the contents of alert.php to poor old alert() from javascript. I would personally separate out the projects into languages at this stage (do something purely in javascript, purely in php, etc.) and start mixing them together when I felt ready.
You don't need javascript to assign a value to a form's action attribute. This can be done inside the form tag itself.
Please let me know if anything needs to be explained further.
Update: here are the code samples you have requested. I went through your code and "fixed" it. Important notes: you should pick a formatting standard and stick to it. Examples:
You connect to the database in 2 different places in 2 different ways, you should have a single database connection file that you include in all the relevant php's.
Your quotation marks are sometimes single and sometimes - double, I personally only use double quotes when necessary or convenient (SQL queries, strings containing special characters like "\n").
Indentation wasn't following any particular logic, and empty lines were everywhere; it's important that you format your code so that you and others can read it in a few months when no-one remembers what the hell it was about.
In your test.php you have a table nested inside a div, nested inside a form, nested inside a div - that's hardly necessary.
Why are there empty td and th tags present?
You should pay close attention to how your HTML tags are closed: I've noticed a few " > and " />. Of course, browsers won't care for the most part, but your code readability suffers.
HTML attributes are always lowercase, as far as I know (onClick should be onclick, etc.).
Your table layout is strange, but I didn't touch it. I have no idea why you have a colspan="4" element in every row.
Method names (GET and POST) should always be uppercase (except in XHTML where it's the other way around).
1) test.php
<!DOCTYPE html>
<!--[if lt IE 7]><html class="ie ie6" lang="en"><![endif]-->
<!--[if IE 7]><html class="ie ie7" lang="en"><![endif]-->
<!--[if IE 8]><html class="ie ie8" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>--</title>
<script>
function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
var xmlHttpRequest = new XMLHttpRequest();
var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
xmlHttpRequest.open(method, url, async);
xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
xmlHttpRequest.send(param);
if(!async) { callback(xmlHttpRequest); }
}
function checkAddress(e) {
var checkbox = e.target.parentNode.parentNode.querySelector('[type="checkbox"]');
if(checkbox) {
ajaxQuery('alert.php', 'POST', 'users[]='+checkbox.value, true, function(request) {
alert(request.responseText);
}, function() { alert('Shiver me timbers!'); });
} else {
alert('Please select a checkbox to update.');
}
}
</script>
</head>
<body>
<h1 style="text-align: center;"></h1>
<?php
$conn = mysqli_connect('localhost', 'root', '11111111');
mysqli_select_db($conn, 'test');
$result = mysqli_query($conn, "SELECT * FROM inputs ORDER BY userId DESC");
?>
<div class="form-style-1">
<form name="frmUser" method="POST" action="test.php">
<div style="width: 1200px;">
<table style="text-align: center;" border="0" cellpadding="10" cellspacing="1" width="1200" class="tblListForm" align="center">
<tr class="listheader">
<td></td>
<td>SN</td>
<th>Domain</th>
<th>Department</th>
<th></th>
</tr>
<?php
$i=0;
$j=1;
while($row = mysqli_fetch_array($result)) {
$classname = $i%2==0 ? 'evenRow' : 'oddRow';
?>
<tr<?php if(isset($classname)) { echo ' class="'.$classname.'"'; } ?>>
<td>
<input type="checkbox" name="users[]" value="<?=$row["userId"];?>">
</td>
<td><?=$row["userId"];?></td>
<td><?=$row["department"];?></td>
<th colspan="4">
<input type="button" name="update" class="button" value="Apply" onclick="javascript: checkAddress(event);">
</th>
</tr>
<?php
$i++;
$j=$i+1;
}
$conn->close();
?>
</table>
</div>
</form>
</div>
</body>
</html>
2) alert.php
<?php
$servername = 'localhost';
$username = 'root';
$password = '11111111';
$dbname = 'test';
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if($conn->connect_error) { die('Connection failed: '.$conn->connect_error); } // Check connection
if(isset($_POST['submit'])){
$rowCount = count($_POST['users']);
$num_var= '';
$queried_name = '';
for($i=0; $i<$rowCount; $i++) {
$num_var = mysqli_real_escape_string($conn, $_POST['users'][$i]);
$result = mysqli_query($conn, "SELECT * FROM inputs WHERE userId='".$num_var."'");
if(!$result) { die('MySQL Error: '.mysqli_error($conn)); }
while($row[$i]= mysqli_fetch_array($result)) {
$queried_name = $row[$i]['department'];
echo "Please refer to the following department: $queried_name\n";
}
}
}
$conn->close();
?>
First, alert('something'); is a JavaScript sentences. It must be written inside <script>alert(0)</script> tag or some attributes like onclick="alert(0)",so that the browser can excute it.
Second, AJAX is a technology which also be written in JavaScript. You must make sure the url AJAX requesting to can return data as response. The simplest php file the AJAX requesting to may like this <?php echo 'hello world.'?>.So, when the AJAX request send to the php file url, you will get a response data 'hello world.' Here is a useful website for AJAX learning. MDN/AJAX

Why is mysql data not pulling into form despite query finding record, does look up value need to be unique?

I have the following code which is supposed to pull data from mysql database if search box value matches row & attribute Client_Name in MYSQL.
please see http://www.recruitingblt.comli.com/add-new-sales-record.html.
When a match is found, the form reverts back (try James Dean) and does not autopopulate the fields I want it to (for now I am just asking for Client_Address, Client_Phone & Attn_Email1 to test). These are the names of columns in mysql table bltrecruiting).
I am thinking that maybe Client_Name needs to be unique, say I have company Microsoft, and there is more than one row, will the query not be able to pull through address, phone etc despite being the same for all Microsoft records? Does the look up value need to be unique?
<?php
$regnum = $_GET['regnum'];
//////////regnum is named box at top of form page (Client Name Box)
//////Connection which seems to work fine
$db_host = 'mysql6.000webhost.com';
$db_username = '********';
$db_password = '********';
$db_name = 'a8748341_bltrec';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
////// Check for the Client Name which is a field Client_Name in the database - Should Client_Name be unique?
$result = mysql_query("SELECT * FROM bltrecruiting WHERE Client_Name='$regnum'") or
die(mysql_error());
$row = mysql_fetch_array( $result );
if (empty($row[Client_Name]))
{
echo "No previous record of Client: $regnum <br>";
echo "Please try again <br>" ?>
<div id=regcon>
<FORM NAME = "reg" action=database.php>
<div style=width:150px; float:left; display:inline-block; font-family: Verdana;
font-size: 12px; padding-left:13px;> Client Name: </div>
<input type="text" id="textbox" name="regnum" size="20"/>
<input name="Submit" type="submit" value="Get Form"/>
</form>
</div>
}
else
{
///////// Get the fields from the database
$address = $row['Client_Address'];
$phonenumber = $row['Client_Phone'];
$name= $row['Attn_Name1'];
//add your additional fields here
echo '<script type="text/javascript"src="http://form.jotform.com/jsform/43438603456356?"Client_Name='.$regnum.'&Client_Address='.$address.'&Client_Phone='.$phonenumber.'&Attn_Name1='.$name.'"></script>';
}
?>
</body>
</html>
i noticed that your empty($row[Client_Name]) did not have quotes around it but I tested the below code. Even tho you might have more than 1 row, your $row variable will have data for row 1 in its index (you are not doing a while loop thru the mysql_fetch_array).
if (!is_array($row) && empty($row['Client_Name']))
{
echo "No previous record of Client: $regnum <br>";
echo "Please try again <br>";
?>
<div id=regcon>
<FORM NAME = "reg" action=database.php>
<div style=width:150px; float:left; display:inline-block; font-family: Verdana;
font-size: 12px; padding-left:13px;> Client Name: </div>
<input type="text" id="textbox" name="regnum" size="20"/>
<input name="Submit" type="submit" value="Get Form"/>
</form>
</div>
<?php
}
else
{
///////// Get the fields from the database
$address = $row['Client_Address'];
$phonenumber = $row['Client_Phone'];
$name= $row['Attn_Name1'];
//add your additional fields here
echo '<script type="text/javascript"src="http://form.jotform.com/jsform/43438603456356?"Client_Name='.$regnum.'&Client_Address='.$address.'&Client_Phone='.$phonenumber.'&Attn_Name1='.$name.'"></script>';
}
i did a test locally and faked some values into the javascript URL - should they appear in that form?

Categories