Comments on Posts (PHP) - javascript

I'm currently trying to use comments on my website. The comments will be used on posts I have.
The thing is, I'm currently using an iframe to show them.
I would like the code to be on the same page as my posts.
I'll show you what I mean by posting my code:
comment_frame.php:
<?php
if (isset($_POST['postComment' . $getid . ''])) {
$post_body = $_POST['post_body'];
$posted_to = "Chris";
$insertPost = mysql_query("INSERT INTO post_comments VALUES ('','$post_body','$user','$posted_to','0','$getid')");
echo "<p style='color: green'>Comment Posted!</p><br /><br />";
}
// Get relevent comments
$get_comments = mysql_query("SELECT * FROM post_comments WHERE post_id='$getid' ORDER BY id DESC");
$count = mysql_num_rows($get_comments);
if ($count != 0) {
while ($comment = mysql_fetch_assoc($get_comments)) {
$comment_body = $comment['post_body'];
$posted_to = $comment['posted_to'];
$posted_by = $comment['posted_by'];
$removed = $comment['post_removed'];
echo "<b><a href='$posted_by' target='_blank'>$posted_by</a> said: <br /></b>".$comment_body."<hr /><br />";
}
}
else
{
// Do nothing!
}
?>
home.php:
<?php
// If the user is logged in
$getposts = mysql_query("SELECT * FROM posts WHERE user_posted_to='$user' ORDER BY id DESC LIMIT 10") or die(mysql_error());
while ($row = mysql_fetch_assoc($getposts)) {
$id = $row['id'];
$body = $row['body'];
$date_added = $row['date_added'];
$added_by = $row['added_by'];
$user_posted_to = $row['user_posted_to'];
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$added_by'");
$get_info = mysql_fetch_assoc($get_user_info);
$profilepic_info = $get_info['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/default_pic.png";
}
else
{
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
?>
<script language="javascript">
function toggle<?php echo $id; ?>() {
var ele = document.getElementById("toggleComment<?php echo $id; ?>");
var text = document.getElementById("displayText<?php echo $id; ?>");
if (ele.style.display == "block") {
ele.style.display = "none";
}
else
{
ele.style.display = "block";
}
}
</script>
<?php
echo "
<br />
<div class='newsFeedPost'>
<div class='newsFeedPostOptions'>
<a href='javascript:;' onClick='javascript:toggle$id()'>Show Comments</a>
<div style='float: left;'>
<a href='$added_by'><img src='$profilepic_info' height='60' /></a>
</div>
<div class='posted_by'><a href='$added_by'>$added_by</a> wrote:</div>
<br /><br />
<div style='max-width: 600px; height: auto;'>
$body<br /><br /><br /><p />
</div>
Like – Re-Shout! – Comment
<br /><iframe src='./comment_frame.php?id=$id' frameborder='0' style='max-height: 200px; width: 100%; min-height: 10px;'></iframe>
</div>
</div>
";
}
}
?>
As you can see it shows the comment_frame.php page by using an iframe. I would like all of that code to be in a single page. How would I do that?

put ur home.php code in else condition if user adding new comment the first condition will work otherwise second one
if (isset($_POST['postComment' . $getid . ''])) {
your code here
}else {
// home.php code herer
}

Related

Excecuting php when clicking a button

So I've made a database where people can upload pictures to. The pictures are linked to a place which is linked to a category.
I'm trying to create a gallery page that displays all the images, and then the categories available. When you click on a category it's meant to show all the pictures for that category.
I've got my categories in my database as well, which I'm using php to echo out:
<?php
include('includes/connectdb.php');
/* Selects id and name from the table 'category' */
$query = "SELECT id, name FROM category";
$result_category = mysqli_query($dbc,$query);
?>
<h1>Category</h1>
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<button name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?></button>
<?php endwhile; ?>
When a button is clicked I need it to run this php:
<?php
if(isset($_POST['category[]'])){
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
}
?>
I found out that it should be possible with ajax, so I added the following to my ajax.php file:
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'category':
category();
break;
}
}
function category() {
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
exit;
}
?>
And this to my gallery.php file where I'm displaying the pictures and categories.
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
And lastly I changed my button to be
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="submit" class="button" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
I'm linking to the jquery library and I've tested the SQL statement that I need to run, and it works when I specify what the placecategory.category_id is.

Onclick function is not working on a particular span

I am having a problem that my Onclick event is not triggering on a tag. The same onclick event is working properly when binded to a image.
I am making a follow and unfollow function in php and jquery .It is not working so I decided to test a alert after clicking the follow or unfollow button . Then also it is not working .
The code is this
<?php
if ($my_id != $id) {
$check_follow_not = mysqli_query($conn, "SELECT * FROM follower WHERE user_id='$my_id' AND following='$id'");
$check_follow_not_rows = mysqli_num_rows($check_follow_not);
if ($check_follow_not_rows == 0) {
$editfollowunfollow = "<span class='btn_f_uf'><a onclick=\"don();\">Follow</a></span>";
} else {
$editfollowunfollow = "<span class='btn_f_uf'><a onclick=\"don();\">UnFollow</a></span>";
}
} else {
$editfollowunfollow = "<span class='btn_f_uf'><a>Edit Profile</a></span>";
}
echo $editfollowunfollow;
?>
The php code is okay, the problem is with the jquery code
The don() function is this
function don(){
alert();
}
This function is working fine on a image in same file . But not working in the follow and unfollow button.
Thanks in advance . I appreciate all answer
EDIT
Css code of class btn_f_uf
.btn_f_uf{
border:0;
outline:0;
padding:10px;
background:#53a93f;
border-radius:5px;
color:white;
float:right;
margin-right:20px;
margin-top:25px;
display:inline-block;
}
EDIT 2
The profile page whole code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>Profcee</title>
<link rel="stylesheet" href="style/style.css">
<script src="js/jquery-2.1.3.js"></script>
<script src="js/check.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery-ui.min.js"></script>
</head>
<?php
session_start();
if(isset($_GET['id'])){
include "function/checklogin.php";
include "config/connect.php";
$my_profile_image = $_SESSION['profile_image'];
$my_email = $_SESSION['email'];
$my_id = $_SESSION['id'] ;
$my_name = ucfirst($_SESSION['name']);
$my_background_image = $_SESSION['background_image'];
$id = $_GET['id'];
$check = mysqli_query($conn,"SELECT * FROM users WHERE id='$id'");
$check_num = mysqli_num_rows($check);
if($check_num == 0){
header("location:home.php");
}else{
$fetch = mysqli_fetch_assoc($check);
$name = ucfirst($fetch['name']);
$email = $fetch['email'];
$profile_image = $fetch['profile'];
$background_image = $fetch['background'];
if($my_id != $id){
$check_follow_not = mysqli_query($conn,"SELECT * FROM follower WHERE user_id='$my_id' AND following='$id'");
$check_follow_not_rows = mysqli_num_rows($check_follow_not);
if($check_follow_not_rows == 0){
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>Follow</a></span>";
} else{
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>UnFollow</a></span>";
}
}else{
$editfollowunfollow = "<span class='btn_f_uf'><a>Edit Profile</a></span>";
}
?>
<?php
include "header.php"; ?>
<div id="profile_full">
<div id="background_image">
<img src="<?php echo $background_image;?>" width="100%" height="400px" onclick="don();">
</div>
<div id="profile_image">
<img src="<?php echo $profile_image?>" width="250px" height="250px">
</div>
<div id="profile_header">
<h1><?php echo $name;?></h1>
<div id="profile_follower">
<?php
$follower = mysqli_query($conn,"SELECT * FROM follower WHERE following='$id'");
$follower_count = mysqli_num_rows($follower);
?>
<h2><?php echo $follower_count;?> Follower</h2>
</div>
<div id="profile_following">
<?php
$following = mysqli_query($conn,"SELECT * FROM follower WHERE user_id='$id'");
$following_count = mysqli_num_rows($following);
?>
<h2><?php echo $following_count;?> following </h2>
</div>
<?php echo $editfollowunfollow;?>
</div>
</div>
<?php
include "footer.php";
?>
<?php
}
}else{
header("location:home.php");
}
?>
The check.js file
$(document).on("click",".btns", function(e){
e.preventDefault();
alert();
});
Like other said, give it class name btns and removeonclick inline javascript on that anchor tag :
.....
if($check_follow_not_rows == 0){
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>Follow</a></span>";
} else{
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>UnFollow</a></span>";
}
....
And in js code :
$(document).on("click",".btns", function(e){
e.preventDefault();
alert();
});
If you wanna stick with function don(), use this(but must be sure to remove onclick inline javascript) :
$(document).on("click",".btns", don );
In don function :
function don(){
alert();
return false;
}

Show loading image until dynamic content is available and new page is loaded

Here is what I need to do.
I have a php page wich generates a page like site.com/result.php?id=355 plus there is dynamic content fetched from a MySql database.
The problem: The user is redirected to that page before the content even exists in the Mysql database (it is still processed on server side). This means the user has to refresh the page few times for about 3 sec and the results are there.
I want to show a loading image while there is nothing to display until the content is in the database. Once the content can be displayed it should be printed automatically without the user having to refresh page manually.
Code :
File upload and redirect:
">
<input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
<input name="userfile" type="file" id="exampleInputFile">
<p class="help-block">Select File To Crypt.</p>
<!-- <input type="hidden" name="MAX_FILE_SIZE_BIND" value="10485760" />
<input name="binded" type="file" id="exampleInputFile">
<p class="help-block">Select File To Bind</p> -->
<p>
<button type="submit" name="submit" class="btn full-width btn-primary">Crypt and Scan</button>
</p>
</form>
<?php
if (!isset($_POST['submit']))
{
} else
{
mysql_connect("localhost", "scarr", "12345") or
die("Could not connect: " . mysql_error());
mysql_select_db("scar");
$uploaddir = '/var/www/html/upl/';
$_rand = generateRandomString();
$_namerand = $_rand . ".exe" ;
$uploadfile = $uploaddir .$_namerand ;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
if ($_FILES['MAX_FILE_SIZE']['size'] == 0 && $_FILES['MAX_FILE_SIZE']['error'] == 0)
{
}
$linked = "http://192.168.129.137/upl/" . $_namerand;
$sql = mysql_query("INSERT INTO Task (link, name) VALUES ('$linked', '$_rand')");
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
?>
<form name='redirect' action='result.php?name=' method='GET'>
<input type='hidden' name='name' value='<?php echo $_rand; ?>'>
<script type='text/javascript'>
document.redirect.submit();
</script>
</form>
<?php
} else {
}
}
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
?>
Code Result page:
<?php
mysql_connect("localhost", "scar", "12345") or
die("Could not connect: " . mysql_error());
mysql_select_db("scanner");
$namestr = $_GET["name"];
$result = mysql_query("SELECT id,name,Result FROM Results WHERE name = '$namestr'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
?>
<div id="content">
<h1><center><font color="green">{ 0/42 }</font></center></h1>
<table><thead><th>LiveGr Name</th><th>Result</th></thead>
<tr><td>LiveGridSys </td><td><font color ='Red'><?php printf($row[2])?></font></td></tr>
</table>

checked checkbox will remain through pagination

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

jQuery .attr("src") for img not working

This bugs the hell out of me.
<div id="HLrec_preview" style="width: 218px;">
<img src="HLrec.jpg" style="width: 218px;">
<div style="font-weight: bold;" id="title">a</div>
<div id="link">a</div>
<div id="plaintext">a</div>
</div>
<script>
var HL_rec_image_link = $("#HLrec_preview img").attr("src");
alert(HL_rec_image_link);
</script>
Code works perfectly well in jsfiddle
http://jsfiddle.net/t72uQ/
But on my website, it doesn't work. Alert shows up blank.
There must be something external that affects the result, but I can't figure out what.
What could be causing this?
Thanks in advance
More Complete Code:
<input type="button" id="HLrec_input" value="HL Recommends" style="display:block; width:222px;"/>
<div id="HLrec_preview" style="width: 218px;">
<img src="" style="width: 218px;"/>
<div style="font-weight: bold;" id="title"></div>
<div id="link"></div>
<div id="plaintext"></div>
</div>
<script>
$(document).ready(function(e) {
var HLrec = "<?php
if(isset($_GET["ID"]))
echo $row["HL_REC"];
else
echo "0";
?>";
if(HLrec == "1")
{
<?php
$query = "SELECT IMAGE_LINK, TITLE, LINK, PLAINTEXT FROM HL_Rec WHERE ID=" . $_GET['ID'];
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
?>
$("#HLrec_preview img").attr('src', "<?php echo $row["IMAGE_LINK"]; ?>");
$("#HLrec_preview #title").text("<?php echo $row["TITLE"]; ?>");
$("#HLrec_preview #link").text("<?php echo $row["LINK"]; ?>");
$("#HLrec_preview #plaintext").text("<?php echo $row["PLAINTEXT"]; ?>");
}
$("#submit_input").click(function(e) {
//set HLrec data
var HL_rec = 0;
var HL_rec_title = "none";
var HL_rec_link = "none";
var HL_rec_image_link = $("#HLrec_preview img").attr("src");
var HL_rec_plaintxt = "none";
alert(HL_rec_image_link);
if(HL_rec_image_link.length > 0)
{
HL_rec = 1;
HL_rec_title = $("#HLrec_preview #title").text();
HL_rec_link = $("#HLrec_preview #link").text();
HL_rec_image_link = $("#HLrec_preview img").attr('src');
HL_rec_plaintxt = $("#HLrec_preview #plaintext").text();
}
else
HL_rec_image_link = "none";
});
});
</script>
More code!
This code changes the src from an iframe called in the page
//appends the article tags with content
var title = $("#title").val();
var url = $("#link").val();
var plaintxt = $("#plaintext").val();
//inject html
$("#HLrec_preview img", parent.document).attr('src', newfile);
$("#HLrec_preview #title", parent.document).text(title);
$("#HLrec_preview #link", parent.document).text(url);
$("#HLrec_preview #plaintext", parent.document).text(plaintxt);
WHOOPS.
Had another line of code that interfered.
Hate when that happens.
This is the bad code
//remove t variable from img src's to re enable caching
$("#content_reader_collumn img, #submit_form img").each(function(index, element) {
$(this).attr("src", $(this).attr("src").substring(0, $(this).attr("src").indexOf('?t=')));
});
just have to change the selector.
Thanks for the help guys
Problem can be here
$("#HLrec_preview img").attr('src', "<?php echo $row["IMAGE_LINK"]; ?>");
Ty this instead
$("#HLrec_preview img").attr('src', "<?php echo $row['IMAGE_LINK']; ?>");
Similarly,
$("#HLrec_preview #title").text("<?php echo $row['TITLE']; ?>");
$("#HLrec_preview #link").text("<?php echo $row['LINK']; ?>");
$("#HLrec_preview #plaintext").text("<?php echo $row['PLAINTEXT']; ?>");
Disclaimer: I didn't test it.

Categories

Resources