Sending form data to page nested in div - javascript

This is my third attempt to find an answer to this question, every other time I was downvoted for one reason or another. So I try this again. I am attempting to send data from a hidden input within a form via ajax. The hidden input gets its value from a php script. Now I can not seem to pull the hidden input value on the receiving page. Now the form I am sending from is generated and propagated within php as is the ajax that fires to send the form to the other page.
When I attempt to call the info from the form on the receiving page it does not seem to receive the data from the first page. The reason I assume this is I get no errors and it will not display the data but it does fire the echo that is located before the fetch array.
Here is the code for the first page. It works in all aspects with what I am trying to do except for the form sending portion. I am leaving a lot out but the ajax and form portions are in there.
<?php
$con=mysqli_connect("localhost","base","password","util");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM recipes";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo"
<script>
$(document).ready(function() {//start document ready
$('#" . $row['id'] ."').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/pages/receivingpage.php',
data: $(\"f2\").serialize(),
success: function(d){
$(\"#content-disp\").html(d);
}
});
});
});//end document ready
</script>
<div id=\"covera\">
<div id=\"holder\" class=\"holder\">
<div id=\"disp\" class=\"disp\">
<div class=\"click diagonal panel\">
<div id=\"" . $row['id'] ."\" class=\"front\">
<form id=\"" . $row['recipe'] ."\" name=\"f2\">
<input type=\"hidden\" name=\"recipe\" value=\"" . $row['recipe'] ."\">
<h2>
" . $row['recipe'] ."<br></h2>
<img src=\"http://localhost/img/" . $row['image'] ."\" alt=\"Recipe Image\" style=\"width:150px;height:100px;\">
</form>
</div>
<div class=\"back\">
<div class=\"pad\">
<h2>" . $row['recipe'] ."</h2>
<p>" . $row['id'] ."</p>
<p>" . $row['id'] ."</p>
<p>Number of Servings " . $row['servings'] ."</p>
<p>Appx. Cooking Time: " . $row['cooking'] ." Minutes</p>
<p>Numer of Calories: " . $row['calories'] ."</p>
</div>
</div>
</div>
</div>
</div>
</div>";
}
mysqli_close($con);
?>
Here is the receiving page. It loads but only displays the echo. If I remove the WHERE within the SELECT statement it displays all the database results(not what is desired).
<?php
$con=mysqli_connect("localhost","base","password","util");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$r = $_POST["f2"]['recipe'];
$sql = "SELECT * FROM recipes WHERE recipe ='".$r."'";
$result = mysqli_query($con,$sql);
echo " 2 ";
while ($row = mysqli_fetch_array($result)) {
echo " " . $row['recipe'] ." ";
}
mysqli_close($con);
?>
Any help will be much appreciated.

Try posting serialized data using id instead of the name of the form. See below the example code.
data: $(\"#f2\").serialize(),
Hope this will help you.
See below updated working code.
UPDATED ANSWER:
page1.php
</script>
<?php
$rows[0]['id'] = 1;
$rows[0]['recipe'] = "Veg Rec";
$rows[0]['cooking'] = "Hot cooking";
$rows[0]['calories'] = 1000;
$rows[0]['image'] = "image.png";
foreach ($rows as $key => $row) {
# code...
echo"
<div id=\"covera\">
<div id=\"holder\" class=\"holder\">
<div id=\"disp\" class=\"disp\">
<div class=\"click diagonal panel\">
<div id=\"" . $row['id'] ."\" class=\"front\">
<form id2=\"" . $row['recipe'] ."\" id=\"f2\">
<input type=\"hidden\" name=\"recipe\" value=\"" . $row['recipe'] ."\">
<h2>
" . $row['recipe'] ."<br></h2>
<img src=\"http://localhost/img/" . $row['image'] ."\" alt=\"Recipe Image\" style=\"width:150px;height:100px;\">
</form>
</div>
<div class=\"back\">
<div class=\"pad\">
<h2>" . $row['recipe'] ."</h2>
<p>" . $row['id'] ."</p>
<p>" . $row['id'] ."</p>
<p>Number of Servings " . $row['servings'] ."</p>
<p>Appx. Cooking Time: " . $row['cooking'] ." Minutes</p>
<p>Numer of Calories: " . $row['calories'] ."</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {//start document ready
$('#" . $row['id'] ."').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'page2.php',
data: $(\"#f2\").serialize(),
success: function(d){
$(\"#content-disp\").html(d);
}
});
});
});//end document ready
</script>
";
}
?>
page2.php
<?php
print_r($_POST);
?>

Related

Prepared statement to make pictures show up on php page, when JOINING tables

I currently have a loginsystem where a user is able to register and login as a user.
My system is based on PHP PDO.
When the user is logged in they should be able to upload a picture which is linked to their account.
Right now i have a fully functional loginsystem so thats great, and the user is currently able to upload a picture to the database, but he cant yet see it on the site.
Right now my problem is to make the pictures show up on the site.
I want the user to be able to see his OWN pictures that he uploaded, and not anybody elses pictures.
This is what i have so far! :)
This my Database!
TABLE PICTURES with the following rows:
descPicture
id
imageFullNamePicture
titlePicture
userid
TABLE USERS with the following rows:
user_email
user_id
user_name
user_password
user_phone
user_zip
This is my CODE so far:
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chhoe17";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $e) {
echo $e->getMessage();
}
UPLOAD.INC.PHP
<?php
include "../upload.php";
//Find the ID of the USER
// session_start();
include_once 'dbh.inc.php';
$pictureTitle = ($_POST["filetitle"]);
$pictureText = ($_POST["filedesc"]);
//Fnd ID from the user
//$user = $_SESSION["u_id"];
$user = $_SESSION['u_id'];
$queryUserID = 'SELECT user_id from '.'users'. ' where user_name="'. $user.'";';
$stmt = $conn -> prepare($queryUserID);
$stmt -> execute();
$result = $stmt -> fetch(PDO::FETCH_ASSOC);
//FileDic
$fileDirectory = "../uploads/";
$fileHandled = $fileDirectory . basename($_FILES["file"]["name"]);
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
if (move_uploaded_file($_FILES["file"]["tmp_name"], $fileHandled)) {
//echo "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
$picture = 'INSERT INTO pictures (titlePicture, descPicture, userid, imageFullNamePicture)
VALUES (:titlePicture, :descPicture, :userid, :imageFullNamePicture);';
$stmt = $conn->prepare($picture);
$stmt -> bindParam(":titlePicture", $pictureTitle);
$stmt -> bindParam(":descPicture", $pictureText);
$stmt -> bindParam(":userid", $user);
//$stmt -> bindParam(":userid", $result['user_id']);
$stmt -> bindParam(":imageFullNamePicture", $fileHandled);
$stmt -> execute();
header("Location: ../upload.php?`Success");
?>
<?php } else {
header("Location: ../upload.php?Error");
//echo "Sorry, there was an error uploading your file.";
}
header("Location: ../upload.php");
UPLOAD.PHP
<body>
<section class="main-container">
<div class="main-wrapper">
<h2>Manage your pictures</h2>
<?php
//display a message and images if logged in!
if (isset($_SESSION['u_id'])) {
echo "Upload your pictures";
echo '<div class="picture-upload">
<h2>Upload</h2>
<br>
<br>
<br>
<form action="includes/upload.inc.php" id="upload" method="POST" enctype="multipart/form-data">
<input type="text" name="filetitle" placeholder="Image title">
<input type="text" name="filedesc" placeholder="Image description">
<input type="file" id="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>';
}
if (isset($_SESSION['users'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="pictures">
<a target="file" href= <?php ?>>
<img class="pic" src= <?php echo $data['imageFullNamePicture']; ?>></a>
<div class="titlePicture"><?php echo $data['titlePicture']; ?> <br> </div>
<div class="descPicture" >Your description:</div>
<div class="text"><?php echo $data['titleDesc']; ?> <br> ?> </div>
</div>
<?php
}
};
?>
</div>
</section>
</body>
</html>
<?php
include_once 'footer.php';
?>
So yea the problem is that i cant get the pictures that connects to the currently logged in user to show up on the page upload.php
I hope that somebody can help me! :)
EDIT!!!:
So i currently have this piece of code. IT should make the user see the pictures that he uploaded to the database, but it is very buggy. And it only shows one picture per user. Can somebody help make this work.
if (isset($_SESSION['u_id'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
?>
<div id="pictures">
<?php
$sql = "SELECT * FROM pictures WHERE userid = '{$_SESSION['u_id']}'";
//$sql = "SELECT * FROM pictures ORDER BY userid DESC LIMIT 20;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$pictures = $stmt->fetchAll();
// if ($pictures !== null) {
foreach ($pictures as $pic)
?>
<figure id="<?php echo $pic['id']; ?>">
<b><figcaption><?php echo $pic["titlePicture"] ?>
<img src = <?php echo $pic["imageFullNamePicture"] ?>>
<?php echo $pic["descPicture"] ?> <br>
</figure>
<?php
// }
}
?>
</div>
Your fetching the data as numerically indexed arrays PDO::FETCH_NUM, yet your using the keys in your code:
UPLOAD.INC.PHP
//instead of PDO::FETCH_NUM
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
...
<?php echo $data['imageFullNamePicture']; ?>
...
<?php }
Use PDO::FETCH_ASSOC instead.
Please don't do this with PDO:
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
If someone manages to get data in here name="' . $_SESSION['u_id'] . '" you've just defeated the whole purpose of preparing your SQL. It shouldn't matter where that data came from, you never know when a simple coding mistake or something will allow user data into a session variable.
$user_data = 'SELECT * FROM users INNER JOIN pictures on users.user_id
= pictures.userid WHERE name=:u_id';
$stmt = $conn->prepare($user_data);
$stmt->execute(['u_id'=>$_SESSION['u_id']]);
It's that easy to prepare it properly. You don't really need to even use bind whatever with PDO, unless you wan't to restrict the Type. But I think it's also the only way to do LIMIT :limit. Anyway I almost never use them. In general both PHP and MySQL are smart enough to do the proper type casting.
PS. don't forget to call session_start() if your using $_SESSION or none of that will work. I didn't see it in the code that was posted, so I have to mention it.

buttons in forms doesnt work after ajax call from db

I have search google, here and w3schools but this answer i cant find anyway. Not even in the "questions that may already have your answer".
I am trying to learn a bit more about AJAX and i have come to a hold at this guide W3schools AJAX database
All the guide i can get to work but when i try to suit it to my needs it goes wrong. What i want is that when i get to "getuser.php" i want to be able to update db in this file. If possible without me leaving this page with the result i have found. I choose from a dropdown table before this site. The php files which is supposed to update the db works (tried them on a normal page, and all is good). My current workaround is to add a button which opens a second window to update the info.
When i get to this point:
<?php
$q = intval($_GET['q']);
include 'db.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"webhelp");
$sql="SELECT * FROM advisors WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<table><tr><td>Phone</td><td>" . $row['phone'] . "</td>
<td><form action='addphone.php' method='post'>
<input type='hidden' name='id' value='".$q."'>
<td><input type='text' name='phone'></td>
<td><input type='submit' value='Update'></td>
</form></td></tr></table>";
echo "<tr><td>LoB</td><td>" . $row['lob'] . "</td>
<td><form action='addlob.php' method='post'>
<input type='hidden' name='id' value='".$q."'>
<td><select name='lob'>
<option value='". $row['lob'] ."'>" . $row['lob'] . "</option>".
$sql = "SELECT * FROM lob";
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["lob"] . "'>" . $row["lob"] . "</option>"; }
"</select></td>
<td><input type='submit' value='Update'></td>
</form>
</tr>";
echo "<tr><td>Country</td><td>" . $row['country'] . "</td>
<td><form action='addcountry.php' method='post'>
<input type='hidden' name='id' value='".$q."'>
<td><select name='country'>
<option value='". $row['country'] ."'>" . $row['country'] . "</option>".
$sql = "SELECT * FROM country";
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["country"] . "'>" . $row2["country"] . "</option>" ; }
"</select></td>
<td><input type='submit' value='Update'></td>
</form>
</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The "Update" buttons doesnt work. It doesnt matter where i place the files (same folder, different folder) ect. However if i add a button with a link outside of the then that button work. But as soon as it is inside a table PLUS also method="post" is in the form it mess it up.
What am i doing wrong?
Alternatively is it possible to make a button here which carries the $id over to a small popup window? (I can open it in a new window but I can't choose how big the window should be)
You want to do this for all your 3 forms. I give you example for first one.
Form
echo "<form class='addPhoneForm' action='addphone.php' method='post'>
<table>
<tr>
<td>Phone</td><td>" . $row['phone'] . "</td>
<td><input class='phoneID' type='hidden' name='id' value='".$q."'></td>
<td><input class='phoneNumber' type='text' name='phone'></td>
<td><input class='submitme' type='submit' value='Update'></td>
</td>
</tr>
</table>
</form>";
AJAX
$(document).ready(function(){
$(".submitme").click(function(){
//collect variables from input
var phoneID = $(".phoneID").val();
var phoneNumber = $(".phoneNumber").val();
// store in a string
var dataAddPhone = 'phoneID='+ phoneID + '&phoneNumber='+ phoneNumber;
// send to database
$.ajax({
type: "POST",
url: "addphone.php",
data: dataAddPhone,
cache: true,
//if success
success: function(response){
//display message
$(".displayMessage").html(response);
//and reset form
$(".addPhoneForm").trigger("reset");
}
});
return false;
});
});

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.

making an accordion toggle that works with php

how can i make a simple accordian toggle like in https://www.wireshark.org/download.html that works like getting data from a database i have,which has questions and answers? that works simply for all the rows.
this is the current code i have and want to modify.
<?php
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', ''));
((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . 'db'));
$query = "SELECT * FROM AS_Questions";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if (!$result) {
printf("Errormessage: %s\n", $mysqli->error);
}
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "<div class='span3 tiny'>
<div class='pricing-table-header-tiny'>
<h2>" . $row['Question'] . "</h2>
</div>
<a href='##' id='s'>Show answer</a>
<div class='dq'>
<div class='pricing-table-features'>
<p>" . $row['Answer'] . "</p>
</div>
<div class='Dass'>
<p id='Dassp'>Answered by:" . $row['Doctor'] . "<p>
</div>
</div>
</div>"; //$row['index'] index here is a field name
}
echo "</table>"; //Close the table in HTML
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
?>

how to display the uploaded file contents on the same page without refreshing?

I have the following html and php codes to read a uploaded file in a html page and display its contents in another new page, but i want the display the file contents in the same html page without opening a new tab and refreshing, how can I achieve that ?
HTML:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP:upload_file.php
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
You can use iframe
html
<html>
<body>
<script>
function ajaxFileUpload(upload_field)
{
var filename = upload_field.value;
upload_field.form.action = 'upload_file.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
return true;
}
</script>
<iframe name="upload_iframe" id="upload_iframe" ></iframe>
<form action="#" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" onchange="return ajaxFileUpload(this);">
</form>
</body>
</html>
upload_file.php
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"]. " <br>";
$content = file_get_contents($_FILES["file"]["tmp_name"]);
echo "Content: ".$content;
}
?>
You can check whether the submit button is clicked or not using php and then proceeding to display the data.
PHP: upload.php
<?php
//checks if the submit button is submitted
if(isset($_POST['submit']) && $_POST['submit'] == "Submit") {
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
?>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Categories