Undefined variable from php to js - javascript

I've got a loop posting images from database.
I tried to give each photo div separate id.
When i tried to send it to script by onclick function
It shows that "$photoid is not defined "
I tried to print this variable in this first php script but it shows me all IDs, so shouldnt be empty or undefined...
$allphotos = mysql_query("SELECT * FROM photos ORDER BY id DESC");
while ($numphotos = mysql_fetch_assoc($allphotos)){
$photoinfo = mysql_query('SELECT * FROM photos WHERE link="'.$numphotos['link'].'" ');
$fetchinfo = mysql_fetch_assoc($photoinfo);
$photoid = $fetchinfo['id'];
echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick=clicked($photoid)></div>';
}
Here goes script:
<script>
function clicked(photoid){
document.getElementById('photoid').style.backgroundColor = 'red'
}
</script>

Change this:
echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick=clicked($photoid)></div>';
to this:
echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick="clicked('.$photoid.');"></div>';
otherwise, the output is just clicked($photoid), all text.
Also change that:
function clicked(photoid){
document.getElementById('photoid').style.backgroundColor = 'red'
}
to that:
function clicked(photoid){
document.getElementById( photoid.toString() ).style.backgroundColor = 'red';
}

The answer above is working, but they forgot to add something,
instead of
echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" onclick="clicked('.$photoid.');"></div>';
copy this code
echo '<div class="thisphotobox" id="'.$photoid.'"><img src="'.$numphotos['link'].'" alt="photo" class="photolink" style="background-color:white" onclick="clicked('.$photoid.');"></div>';
add the style="background-color:white;" i think you can't access the .style in js if you didn't initialize it in your div. hope this will help

This is simply an escaping issue. The argument $photoid in your echoed function has to be escaped if it is a string. In your code above this:
onclick=clicked($photoid)
should be
onclick="clicked($photoid)"
if $photoid is a number or
onclick="clicked(\'$photoid\')"
if it is alphanumeric or a string

Related

How to display text saved in DB, properly in HTML?

I am creating an application using PHP and MySQL.
In the DB, the data is saved in the following manner:
But, while displaying the result in HTML page, the result comes like this:
The issue might be because HTML needs tags like "<br/>", etc......
How can I display the result in actual format?
Here's the code section displaying the data:
<div class="com-text">
<?php echo $row['chatDesc'];?>
</div>
EDIT:
Also, I need to display the data by creating a div using jquery(dynamically). So how to display it in javascript format too?
html += '<div class="com-text">'+data.chat[i].chatDesc+'</div>';
$("#chat_list").append(html);
Use the below simple CSS
.com-text{
white-space: pre-wrap;
word-wrap: break-word;
}
You should use nl2br which inserts line breaks where newlines occur in a string
the javascript equivement of this function + your code:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' :
'<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
html += '<div class="com-text">'+nl2br(data.chat[i].chatDesc, true)+'</div>';
$("#chat_list").append(html);
You can try this.
<div class="com-text">
<pre> <?php echo $row['chatDesc'];?> </pre>
</div>
$orig = "I'll \"walk\" the dog now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
You should use nl2br which inserts line breaks where newlines occur in a string
<div class="com-text">
<?php echo nl2br($row['chatDesc']);?>
</div>
Just use the nl2br() function to format it:
<?php
$mychat = nl2br($row['chatDesc']);
?>
Here is how you can do..
<div class="com-text">
<?php echo $mychat; ?>
</div>
use nl2br();
<div class="com-text">
<?php echo nl2br($row['chatDesc']) ;?>
</div>

Passing arguments from PHP to javascript

This is the PHP code . I am try to call edit_course() function defined in javascript , passing arguments . But not able to complete the task .There is some problem with this piece of code. But I am not able to figure out .
Is there some better way to do so, which is not so messed up ?
Help will be appreciated.
php
$course_result = $con->query("SELECT * from course_records where institute_id='".$row['institute_id']."' ");
$course=$course_result->fetch_assoc();
echo "<div class='options'> <span ><div class='round-button' id='".$course["course_id"]."' onclick='edit_course(".$course['course_id'].",".$course['subject'].")'><div class='round-button-circle'></div></div> <label class='lblname' >Edit</label></span>";
javascript
function edit_course(course,institute){
alert(course);
alert(institute);}
The output is blank page.
Change it to this, there were some errors:
echo "<div class='options'><span><div class='round-button' id='".$course["course_id"]."'
onclick='edit_course(".$course['course_id'].",".$course['subject'].")'><div>
class='round-button-circle'></div></div> <label class='lblname'>Edit</label></span>";
fetch_assoc() returns an array http://php.net/manual/es/mysqli-result.fetch-assoc.php , you can not use it in the way you are using it, you should iterate over the array to return the results, like this:
$course_result = $con->query("SELECT * from course_records where institute_id='".$row['institute_id']."' ");
$course=$course_result->fetch_assoc();
foreach($course as $value){
echo "<div class='options'> <span ><div class='round-button' id='".$value["course_id"]."' onclick='edit_course(".$value['course_id'].",".$value['subject'].")'><div class='round-button-circle'></div></div> <label class='lblname' >Edit</label></span>";
}

How to show/hide a div independently among others with the same class name within a loop

i have a while loop within an SQL query that returns all comments for a specific post page , within that same loop i have another query and a while loop that searches for replies to that comment and returns only the first row using LIMIT 1. I did this so only one reply is shown for a comment at first, i added another another query and a loop within the second loop to search for other replies to the comment except this time I'm returning the other rows except the first row using LIMIT 1,18446744073709551615. I've put the result of the last query in a div which is hidden at first, and a trigger view all replies in the first query which comes before the hidden div.
So now i have a trigger view all replies inside the first loop (that contains the comments). using javascript i can show and hide the div when the trigger is clicked. this is a snapshot of what it looks like
First snapshot, div is hidden with only 1 reply being shown.
second snapshot, div is visible and text for trigger is changed
My problem:
Since I'm using the same class for all hidden div's, the trigger for a particular comment to show/hide its replies works for all comments. so when i click on view all replies for the first comment, the replies for the second,third etc are shown as well. How do rewrite my code to target specific comments to show/hide its replies?
JavaScript
<html>
<head>
<script language="JavaScript">
$(document).ready(function(){
var showText='View all replies';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links
$('.view1').prev().append();
$(".licom").hide();
$(".view1").click(function(){
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
$('.licom').toggle(function() {
$(this).closest('view1').find('.licom').hide();
return false;
},
function() {
$(this).closest("view1").next(".licom").show();
return false;
});
});
});
</script>
</head>
<body>
</body>
</html>
info.php
<?php
...........
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
while($obj = $stmt->fetch()){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id1 = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
//trigger to hide/show replies
echo '<span class="view1" style="float:right;margin-top:-15px;">View all replies</span>';
//
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
//Relpy to comment, show only the first row
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
//...........same output as first without the view all replies trigger......
//Relpy to comment, show from 2-
$rep = $conn->prepare("SELECT * FROM reply WHERE comment_id = :comid LIMIT 1,18446744073709551615");
$rep->bindParam(":pid", $id1, PDO::PARAM_INT);
$rep->execute();
while($obj = $rep->fetch()){
//div to show/hide
echo '<div class="licom">';
//...........same output as first without the view all replies trigger......
}
}
}
?>
$('.licom').toggle()... is too broad and will select all elements with the 'licom' class, regardless of whether or not they were inside of the element that was clicked. Try $(this).children('.licom') instead.
Since you already have a unique comment ID, you could add that as an ID attribute to your comment-container element, similar to this:
echo '<div class="comment-container" id="comment-' . $id . '">';
Then, your jQuery for toggling the comments (only within that container) would look something like this:
//When a user clicks "View all replies"...
$('.view1').click(function() {
//Find the ID of the comment container he/she clicked inside
var commentID = $(this).closest('.comment-container').attr('id');
//Use that ID to make the selector more specific when targeting the reply elements
$('#' + commentID + ' .licom').toggle();
});
In other words, your jQuery/CSS selector just needs to be more specific.
Also, if you want to add a little bit of (subtle) animation to the show/hide behavior, jQuery's toggle() function accepts several options for accomplishing this: http://api.jquery.com/toggle/
UPDATE
I just realized that your .licom elements are not inside the .comment-container element like I originally assumed. So here's a modified version of my answer that allows you to keep your existing HTML structure.
In addition to outputting the comment ID as the id attribute on the .comment-container (that first line of PHP in my original answer), you also need to output it as a class on each .licom, like this:
echo '<div class="licom comment-' . $id . '">';
Then, the jQuery looks like this:
//When a user clicks "View all replies"...
$('.view1').click(function() {
//Find the ID of the comment container he/she clicked inside
var commentID = $(this).closest('.comment-container').attr('id');
//Use that ID to make the selector more specific when targeting the reply elements
$('.licom.' + commentID).toggle();
});
i've changed my triggers to be unique
echo'View all replies';
and my div class to show/hide to be unique as well by group.
echo '<div class="licom licom-'.$cc_id.'">';//$cc_id has the same value as trigger. example $id1=2, $cc_id=2.
now i have the trigger as licom-1 and div to show/hide as licom licom-1
then i changed my javascript to:
<script language="JavaScript">
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
var id = $(this).attr('id');
if($('.'+id).css('display') == 'none')
{
$('.'+id).css('display','block');
}
else
{
$('.'+id).css('display','none');
}
return false; // cancel original event to prevent form submitting
})
})
</script>
This javascript would only show/hide the div with same licom value i.e only the replies with same id would be toggled by that trigger.
and lastly to make all licom hidden, i added the css.
.licom {
display:none;
}

javascript function with 2 arguments is not working

DEscription :
I have a php script that displays the div on an html page
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id)"></div>';
Now when I click on this div the star_it function gets called and it works perfect...
The problem
I want to pass another argument in the star it function .. like this
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,'.$each_status['regno'].')"></div>';
or a simple alphabet if any like star_it(this.id,s)
but when I do so the function stops working as when I click the div the function does not gets called ....
I dont know why I am stuck and now my star rating system does not work... I have absolutely no idea what is wrong
Anyone ??
You should modify your string quote's like this :
<?php
$status = "second test";
echo '<div class="star_box" id="'.$id.'" onmousedown="star_it(this.id,'."'".$status."'".');" >Hello</div>';
?>
<script>
function star_it(foo1,foo2){
console.log(foo1);
console.log(foo2);
}
</script>
This example works for me.
So with your code :
<?php
echo '<div class="star_box" id="'.$id.'" onmousedown="star_it(this.id,'."'".$each_status['regno']."'".');" >Hello</div>';
?>
Here you go
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,\''.$each_status['regno'].'\')"></div>';
you forget to add \' before and after your string , the JS engine on the browser will treat your string as an undefined variable and the function will not work because of that .
//my English is not so good.
Try
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,\"'.$each_status['regno'].'\")"></div>';

show div based on textbox value

I have a input field that gets it value from a db lets say the value is M,K,H,J,V or G depending on the value it needs to open the div with aaa,bbb,ccc,ddd,eee or fff as text.
The code that is displayed on the page is as followed i left out the retrieval part from the db that part is working (the input box shows M,K,H,J,V or G depending on the id.)
echo "<input type='text' name='periode' id='periode' data-related-item='" .$row['periode']. "' value='" .$row['periode']. "'>";
echo "<div class='hidden'><div id='M'>aaa</div></div>";
echo "<div class='hidden'><div id='K'>bbb</div></div>";
echo "<div class='hidden'><div id='H'>ccc</div></div>";
echo "<div class='hidden'><div id='J'>ddd</div></div>";
echo "<div class='hidden'><div id='V'>eee</div></div>";
echo "<div class='hidden'><div id='G'>fff</div></div>";
When i check the source code in developer mode it shows that the data-related-item part is correctly retrieved from the db:
<input type="text" name="periode" id="periode" data-related-item="M" value="M">
I want to use the following JS but i need to change it to work with textboxes.
<script type="text/javascript">
function evaluate1(){
var item = $(this);
var relatedItem = $("#" + item.attr("data-related-item")).parent();
if(item.is(":checked")){
relatedItem.fadeIn();
}else{
relatedItem.fadeOut();
}
}
$('input[type="checkbox"]').click(evaluate1).each(evaluate1);
</script>
The simplest approach is offcourse changing:
$('input[type="checkbox"]').click(evaluate1).each(evaluate1);
into
$('input[type="textbox"]').click(evaluate1).each(evaluate1);
But what do i need to do with:
if(item.is(":checked")){
Thanks for any help in advance.
I tried the following but it aint working.
if(item.is("M||K||H||J||V||G")){
SOLUTION BY ROBERT ROZAS
The solution is in jsfiddle
http://jsfiddle.net/dXTtz/7/
I made this code based on the code you provide:
$(document).ready(function(){
$("#periode").keyup(function(){
var valor = $("#periode").val();
$(".hidden").each(function(){
var hijo = $(this).children().attr('id');
if(hijo == valor)
{
$(this).removeClass("hidden");
}
});
});
});
Working fiddle here: http://jsfiddle.net/robertrozas/dXTtz/2/
This way is working on page load: http://jsfiddle.net/robertrozas/dXTtz/4/
Page load and removing the extra hidden divs: http://jsfiddle.net/dXTtz/5/

Categories

Resources