Onclick function is not working on a particular span - javascript

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;
}

Related

Calling javascript function from a separate php script?

I have javascript function written within a "generate.php" script and I have "call.php" in a separate script. How do I add a button in "call.php"script that triggers a function in "generate.php"?
"generate.php": javascript; function called by 'save'
<?php
include_once("connection.php");
$chart_data = '';
$db = new dbObj();
$connString = $db->getConnstring();
$id=$_GET['id'];
$query = $connString->prepare("SELECT ID FROM Datas WHERE ID=?");
$query->bind_param('s',$id);
$query->execute();
$result=$query->get_result();
while($row = mysqli_fetch_array($result))
{
$chart_data .= "{ ID:'".$row["ID"]."'},";
}
echo $chart_data;
$chart_data = substr($chart_data, 0);
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP & Mysql</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas#1.0.0-rc.1/dist/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
</head>
<body>
<br /><br />
<div id="chart"></div>
<button id="save">Download</button>
<div class="container" style="width:900px;">
<h2 align="center">MySQL</h2>
<h3 align="center">Data</h3>
<br /><br />
<div id="bar-chart" data-colors="#29abe2,#ffc142,#1ab394, #FF0000, #FFFF00" ></div>
</body>
</html>
<script>
$("#save").click(function() {
html2canvas(document.getElementById('bar-chart')).then(canvas => {
var w = document.getElementById("bar-chart").offsetWidth;
var h = document.getElementById("bar-chart").offsetHeight;
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'pt', [w, h]);
doc.addImage(img, 'JPEG', 10, 10, w, h);
doc.save('xkey.pdf');
}).catch(function(e) {
console.log(e.message);
});
})
</script>
"call.php";
<?php
include_once("generate.php");
$connect = mysqli_connect("localhost", "root", "", "db01");
$output = '';
$sql = "SELECT * FROM Datas WHERE ID LIKE '%" .$_POST["search"]."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<h4 align = "center">Search Result</h4>';
$output .= '<div class="table-responsive">
<table class = "table table bordered">
<tr>
<th>ID</th>
<th>Generate</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["ID"].'</td>
<td><button id="gen" name="generate" class="btn btn-primary"><i class="fa fa"" aria-hidden="true"></i>Generate</button></td>
</tr>
';
}
echo $output;
}
else
{
echo "Data not found";
}
?>
Your pos-PHP code must be located in same document. So either include it via <script src="generate.php"> or via <? require 'generate.php'; ?>
If you need the same functionality in separate scripts, you should extract your js function to a file. Don't forget to name it:
function giveItADescriptiveName() {
html2canvas(document.getElementById('bar-chart')).then(canvas => {
// etc
}).catch(function(e) {
console.log(e.message);
});
}
Then you can include that script in any file where you might need it:
<script src="path/to/where/you/saved/it/whatever-you-called-the-file.js"></script>
And ultimately, you pass your function as the handler:
<script>
$("#save").click(giveItADescriptiveName());
</script>

How do i stop a page from scrolling to the top when button clicked in php?

How do I stop a page from scrolling to the top when button Add to cart is clicked?
since i have a lot of products showing up from database to my page, this refreshing the "index.php" to the top is make me frustrated.
Btw i'm following this tutorial http://www.onlinetuting.com/e-commerce-website-in-php-mysqli-video-tutorials/
PS: i'm a beginner so just help me with an example (the line where to put the code is important for me).
//index.php (short code only)
<!doctype html>
<?php
include ("functions/functions.php");
?>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="styles/style.css" type="text/css" media="all" />
<script src="js/jquery-3.0.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="header"></div>
<div class="navigation">
<div> <?php getCats(); ?> <?php getBrands(); ?> </div>
<div> </div>
<div id="shopping_cart"> Go to Cart <?php total_items(); ?> <?php total_price(); ?> </div>
</div>
<div id="content">
<?php cart(); ?>
<div id="products"> <?php getPro(); ?> <?php getCatPro(); ?> <?php getBrandPro(); ?> </div>
</div>
<div id="footer"></div>
</div> <!--END OF "container" -->
</body>
</html>
//function.php
<?php
$con = mysqli_connect("localhost","root","","learning-php");
if (mysqli_connect_errno())
{
echo "The connection was not established: " . mysqli_connect_error();
}
//Creating the shopping cart
function cart(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$pro_id = $_GET['add_cart'];
$check_pro = "select * from cart where ip_add='$ip' AND p_id='$pro_id'";
$run_check = mysqli_query($con, $check_pro);
if(mysqli_num_rows($run_check)>0){
}
else {
$insert_pro = "insert into cart (p_id,ip_add) values ('$pro_id','$ip')";
$run_pro = mysqli_query($con, $insert_pro);
echo "<script>window.open('index.php','_self')</script>";
}
}
}
//Getting the total added items
function total_items(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$get_items = "select * from cart where ip_add='$ip'";
$run_items = mysqli_query($con, $get_items);
$count_items = mysqli_num_rows($run_items);
}
else {
global $con;
$ip = getIp();
$get_items = "select * from cart where ip_add='$ip'";
$run_items = mysqli_query($con, $get_items);
$count_items = mysqli_num_rows($run_items);
}
echo $count_items;
}
//Getting the total price of the items in the cart
function total_price(){
$total = 0;
global $con;
$ip = getIp();
$sel_price = "select * from cart where ip_add='$ip'";
$run_price = mysqli_query($con, $sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$pro_id = $p_price ['p_id'];
$pro_price = "select * from products where product_id='$pro_id'";
$run_pro_price = mysqli_query($con,$pro_price);
while($pp_price = mysqli_fetch_array($run_pro_price)){
$product_price = array($pp_price['product_price']);
$values = array_sum($product_price);
$total +=$values;
}
}
echo "$ " . $total;
}
//Getting the categories
function getCats(){
global $con;
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li><a href='index.php?cat=$cat_id'>$cat_title</a></li>";
}
}
//Getting the brands
function getBrands(){
global $con;
$get_brands = "select * from brands";
$run_brands = mysqli_query($con, $get_brands);
while ($row_brands=mysqli_fetch_array($run_brands)){
$brand_id = $row_brands['brand_id'];
$brand_title = $row_brands['brand_title'];
echo "<li><a href='index.php?brand=$brand_id'>$brand_title</a></li>";
}
}
//Showing the products
function getPro(){
if(!isset($_GET['cat'])){
if(!isset($_GET['brand'])){
global $con;
$get_pro = "select * from products";
$run_pro = mysqli_query($con, $get_pro);
while ($row_pro=mysqli_fetch_array($run_pro)){
$pro_id = $row_pro['product_id'];
$pro_cat = $row_pro['product_cat'];
$pro_brand = $row_pro['product_brand'];
$pro_title = $row_pro['product_title'];
$pro_price = $row_pro['product_price'];
$pro_image = $row_pro['product_image'];
echo "
<div id='products'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='100'/>
<div class='details'>
<p><div id='prc'>Price:</br><b>$. $pro_price </b></div></p>
<p><div id='a2c'><a href='?add_cart=$pro_id'><button style='float:left;'>Add to Cart</button></a></div></p>
<p><div id='fDtl'><a href='full_details.php?pro_id=$pro_id' style='float:left;'>Full Details</a></div></p>
</div>
</div>
";
}
}
}
}
//Showing the products by categories
function getCatPro(){bla,bla,bla}
//Showing the products by brands
function getBrandPro(){bla,bla,bla}
?>
//what i mean is this line (function.php)
div#a2c
//effected to this line (index.php)
div#products
See What i mean
Override default form submit by calling preventDefault and call the action as a ajax call. Make sure that the script is loaded like put it in head section
refer this example:
var element = document.querySelector("form");
element.addEventListener("submit", function(event) {
event.preventDefault();
// actual logic, e.g. validate the form
alert("Form submission cancelled.");
});
<form>
<button type="submit">Submit</button>
</form>
Here is a complete example from http://www.tutorialspoint.com/jquery/events-preventdefault.htm:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("a").click(function(event){
event.preventDefault();
alert( "Default behavior is disabled!" );
});
});
</script>
</head>
<body>
<span>Click the following link and it won't work:</span>
GOOGLE Inc.
</body>
</html>

Storing User Preferences in Cookie

I'm creating a website in php using which allows users to filter the content displayed through checkboxes. I want to save their preferences. I'm using jquery.mmenu and generating the checkboxes as follows
<form id="menu-right method="post" action="">
<li>
'. $sportArray[$ids]["Event"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
</li>'
</form>
I'm able to collect an array and print the values of the array through the below code, but I'm unable to set cookies, retrieve cookies, and haven't even started adding a check in the checkbox to restore the 'checked' values when loaded the checkboxes. I've tried a number of methods through javascript and php with no luck. There are pseudo elements in the CSS which I understand broke a couple of options for javascript
<?
if(isset($_POST['sportList'])) {
for ($i=0; $i<=count($_POST['sportList']); $i++){
echo $_POST['sportList'][$i];
setcookie('userSportList[$i]', $_POST['sportList'][$i], time()+60*60*24*365, '/');
}
}
?>
Any solution welcome.. it's probably something stupid at this stage as I'm tried so many options now. Alternatives such as localstorage or something also welcome, what ever is the best solution
<?php
if(isset($_POST['sportList'])) {
session_start();
$_SESSION['sesUserPrefs'] = $_POST['sportList'];
$serUserPrefs = serialize($_SESSION['sesUserPrefs']);
$bcSerUserPrefs = base64_encode($serUserPrefs);
$expire = 2000000000;
setcookie("cUserPrefs", $bcSerUserPrefs, time()+$expire);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<title>test
</title>
<link type="text/css" rel="stylesheet" href="css/main.css" />
<link type="text/css" rel="stylesheet" href="css/mmenu.5.3.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/hammer.js/1.0.5/jquery.hammer.min.js"></script>
<script type="text/javascript" src="js/umd.all.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script type="text/javascript">
// The menu on the left
$(function() {
$('nav#menu-left').mmenu();
});
// The menu on the right
$(function() {
var $menu = $('form#menu-right');
$menu.mmenu({
offCanvas: {
position : "right"
},
classes : 'mm-light',
dragOpen : true,
counters : true,
searchfield: {
add: true,
search: false
},
labels : {
fixed : !$.mmenu.support.touch
},
navbars: {
position: "top",
content: [
'Save'
]
}
});
});
</script>
</head>
<body>
<?php
// DB Configuration
$config = parse_ini_file('config/config.ini');
//Timezone dropdown
function timezone() {
$list = DateTimeZone::listAbbreviations();
$idents = DateTimeZone::listIdentifiers();
$data = $offset = $added = array();
foreach ($list as $abbr => $info) {
foreach ($info as $zone) {
if ( ! empty($zone['timezone_id'])
AND
! in_array($zone['timezone_id'], $added)
AND
in_array($zone['timezone_id'], $idents)) {
$z = new DateTimeZone($zone['timezone_id']);
$c = new DateTime(null, $z);
$zone['time'] = $c->format('h:i a');
$data[] = $zone;
$offset[] = $z->getOffset($c);
$added[] = $zone['timezone_id'];
}
}
}
array_multisort($offset, SORT_ASC, $data);
$options = array();
foreach ($data as $key => $row) {
$options[$row['timezone_id']] = $row['time'] . ' - '
. formatOffset($row['offset'])
. ' ' . $row['timezone_id'];
}
return $options;
}
function formatOffset($offset) {
$hours = $offset / 3600;
$remainder = $offset % 3600;
$sign = $hours > 0 ? '+' : '-';
$hour = (int) abs($hours);
$minutes = (int) abs($remainder / 60);
if ($hour == 0 AND $minutes == 0) {
$sign = ' ';
}
return 'GMT' . $sign . str_pad($hour, 2, '0', STR_PAD_LEFT)
.':'. str_pad($minutes,2, '0');
}
?>
<div id="page">
<div id="header">
<!-- Sub Header -->
<form id="tzForm" method="POST" action="">
<select name="userTZ" >
<?php foreach(timezone() as $key => $tz) { ?>
<option value="<?php echo $key; ?>"<?php if ($_POST['userTZ'] == $key) { echo ' selected>';} else { echo '>';} //keep tz as last selected
echo $tz; ?></option>
<?php } ?>
</select> <input type="submit" value="Set">
</form>
</div> <!-- Close Header -->
<div id="content">
<?php
//Collect Selected Sport/Category/Event values from right menu
if (isset($_COOKIE["cUserPrefs"])) {
echo "<script type='text/javascript'>alert('ding ding ding');</script>";
} elseif (isset($_SESSION['sesUserPrefs'])) {
$sportListItem = $_SESSION['sesUserPrefs'];
//update array with selected toggles
while ($row = $result->fetch_array()) {
if ($row['SportCategory'] == $sportListItem OR $row['Sport'] == $sportListItem OR $row['Event'] == $sportListItem) {
$gameArray[ $row['PK_ID'] ] = array(
'GameDate' => $row['GameDate'],
'Timezone' => $row['Timezone'],
'TeamOne' => $row['TeamOne'],
'TeamTwo' => $row['TeamTwo'],
'urlTeamOne' => $row['urlTeamOne'],
'urlTeamTwo' => $row['urlTeamTwo'],
'FK_SportData' => $row['FK_SportData']
);
} //end inside if
};
}
?>
</div>
<div id="page">
<div id="content">
<p id="confirmation"></p>
</div>
<nav id="menu-left">
<?php
foreach ($sportArray as $ids=>$vals) {
//First List Item
if ($ids == 1) {
echo '<ul><li>
'. $sportArray[$ids]["SportCategory"]. '
<ul class="Vertical">';
}
//All others check if different to one before
elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
echo '</ul></li></ul></li><li>
'. $sportArray[$ids]["SportCategory"] . '
<ul class="Vertical">'; //opening thse UL without an event could cause issues
}
//Check the previous sport is not the same
if ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
echo '<li>
'. $sportArray[$ids]["Sport"] . '
<ul class="Vertical">';
}
//Print Event
echo '<li>
'. $sportArray[$ids]["Event"] . '
</li>';
}
?>
</ul></li></ul></li></ul>
</nav>
<form id="menu-right" method="post" action="">
<?php
foreach ($sportArray as $ids=>$vals) {
//First List item
if ($ids == 1) {
echo '<ul class="Vertical"><li>
'. $sportArray[$ids]["SportCategory"]. '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
<ul class="Vertical">';
}
//All others check if different to one before
elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
echo '</ul></li></ul></li><li>
'. $sportArray[$ids]["SportCategory"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
<ul class="Vertical">'; //opening thse UL without an event could cause issues
}
//Check the previous sport is not the same
if ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
echo '<li>
'. $sportArray[$ids]["Sport"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Sport"].'" />
<ul class="Vertical">';
}
//Print Event
echo '<li>
'. $sportArray[$ids]["Event"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
</li>';
}
?>
</ul></li></ul></li></ul>
</form>
</div>
</body>
</html>
You should use session array for this. First store values into a session. Then you need to :
Serialize your session array and apply base64_encode. Put this value
into cookie.
At the start check if cookie exist then apply base64_decode and unserialize that data and push into session array.
If you know about serialize, unserialize, base64_encode and
base64_decode then you can easily do this task.
Hopefully you will done this easily.

Comments on Posts (PHP)

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
}

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