I have A VERY OLD SCRIPT that I need to modify. You will notice from the code it is using mysql_query() which is outdataed however that is not my issue.
I have a text link in a file named surveycommentslist.php. The link opens a jquery model window that I need to capture a user inputed text in and then save it to a mysql along with the value of the links data-id which tells me which unique user ID to connect the comment to. My issue is I am not able to get the value of data-id using the code I have below.
Here is my code
<html>
<head>
<!-- common scripts -->
<!-- jQuery library -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.js"></script>
<!-- jQuery migrate -->
<script src="js/jquery-migrate-1.2.1.min.js"></script>
<!-- bootstrap framework plugins -->
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<script>
$(document).on('click', '.reply', function()
{
//get acommentuid
var val = $(this).attr('data-id');
$.post('surveycommentslist.php', {acommentuid: val}, function(data)
{
console.log(data);
});
});
</script>
<?php
//lets list comments
$scommentsql = mysql_query("SELECT * FROM survey_comments
WHERE surveyid=$surveyid ORDER BY commentdate asc");
while($scrows = mysql_fetch_array($scommentsql))
{
extract($scrows);
$the_comment = stripslashes($the_comment);
$commentdate = date("m/d/Y h:ia", strtotime($commentdate));
if($touid > 0) { $indent = "margin-left:35px"; }
//get name of person making the comment
$nsql = mysql_query("SELECT fname, lname, userlevel, id AS scommentid FROM users WHERE id=$uid LIMIT 1");
$namerow = mysql_fetch_array($nsql);
$commenters_fname = stripslashes($namerow['fname']);
$commenters_lname = stripslashes($namerow['lname']);
if($namerow['userlevel'] > 19)
{
$adminicon = "<img src='./img/admin_smicon.png' alt='admin'>";
}
echo "<div class='ch-message-item clearfix' style='$indent'>
<div class='ch-content'>
$the_comment
</div>
<p class='ch-name'>
<strong>$adminicon $commenters_fname $commenters_lname</strong>
<span class='muted'>$commentdate</span>";
if($touid == 0)
{
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
}
echo "</p>
</div>";
}
$(document).on('click', '.reply', function(e)
{
e.preventDefault();
//get acommentuid
var val = $(this).data('id');
$.post('surveycommentslist.php', {acommentuid: val}, function(data)
{
console.log(data);
});
});
Class attribute is not closed properly. Quotes issue.
Change this
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
to
echo "<a href='#switch_modal' class='reply btn btn-default' id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
Maybe there's just an issue with the single and double quote in the REPLY. You said $scommentid has a value, so I assume there's just an echo problem. Try these:
//codes
.
.
//RE-POSITION class values from id value
echo "<a href='#switch_modal' class='reply btn btn-default btn-small' id='$scommentid' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
//or by concatenation if I am wrong with the above solution
echo "<a href='#switch_modal' class='reply btn btn-default id=".'"$scommentid"'." btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
//or by using the " if I am wrong with the above solutions
echo "<a href='#switch_modal' class='reply btn btn-default id="$scommentid" btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
.
.
//codes
When I copy-paste your code in a file & execute that in a browser, it shows the "data-id" attribute as blank: http://screencast.com/t/pasXI14dp0x . That is due to the incorrect HTML pointed out in earlier messages.
Even after the corrections, there is still the 'btn-small' text which is not in any attribute.
The incorrect HTML is:
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
The correct HTML should be:
echo " <a href='#switch_modal' class='reply btn btn-default btn-small' id='$scommentid' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
Another alternative you could try is hardcode some value in the "data-id" attribute & find out if it's being passed. If that works, then the issue is with the HTML & should be fixed with above corrected HTML code.
Your HTML markup is wrong
You can check that by doing a view source
Change the following code
echo " <a href='#switch_modal' class='reply btn btn-default id='$scommentid' btn-small' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
with
echo "<a href='#switch_modal' class='reply btn btn-default btn-small' id='$scommentid' data-toggle='modal' data-id='$scommentid'>REPLY</a>";
I would suggest to you to return the data from MySQL as JSON using return json_encode($data) which $data is an array of key-value pairs and when you get the data in your script tag / JavaScript, just build the HTML there and add it to a div instead of returning HTML from the server.
When you build your HTML in your script tag / JavaScript, you add the data from the JSON response and loop over the comments.
Maybe that's just me but I like clean code :)
Related
I have the problem that I print the DIV but the content of the foreach is empty and I print NaN, I started to move the accents and quotation marks and now I throw error of a token <. I have been fighting with this for 2 hours and I can't figure out how to make it work.
function activateButtonSend(action){
var addButton = "";
var php = "";
if (action === true) {
php += #php
App\Models\Activity::getOptionsForMail()->map(function($name,$id){
echo "<a class='dropdown-item btn-act-".$id."' href='javascript:sendComments(".$id.");'>".$name."</a>";
});
#endphp
addButton = "<div class='f-flex float-right' id='dropdown-activities'>\
<button id='content-message' style='display: none' type='button' class='btn btn-lg iq-bg-primary-abs dropdown-toggle'\
data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>\
Guardar\
</button>\
<div class='dropdown-menu' aria-labelledby='btnGroupDrop1'>'"+php+"'</div>\
</div>";
}else{
addButton = '<button type="submit" id="content-message" style="display: none" class="btn iq-bg-primary-abs btn-lg float-right action-button-submit">Guardar</button>';
}
$('#type_buttons').html(addButton);
}
Message error console
It prints the results but throws an error because it does not take the tilde to join it inside the php variable of jquery.
#php is the abbreviation of <?php ?>
You're generating JavaScript code, but you're not putting quotes around the JS string. The best way to turn a PHP value into a JavaScript literal is to call json_encode() when echoing.
function activateButtonSend(action){
var addButton = "";
var php = "";
if (action === true) {
php += #php
App\Models\Activity::getOptionsForMail()->map(function($name,$id){
echo json_encode("<a class='dropdown-item btn-act-".$id."' href='javascript:sendComments(".$id.");'>".$name."</a>");
});
#endphp
addButton = "<div class='f-flex float-right' id='dropdown-activities'>\
<button id='content-message' style='display: none' type='button' class='btn btn-lg iq-bg-primary-abs dropdown-toggle'\
data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>\
Guardar\
</button>\
<div class='dropdown-menu' aria-labelledby='btnGroupDrop1'>'"+php+"'</div>\
</div>";
}else{
addButton = '<button type="submit" id="content-message" style="display: none" class="btn iq-bg-primary-abs btn-lg float-right action-button-submit">Guardar</button>';
}
$('#type_buttons').html(addButton);
}
I need to change the class of a span child that uses a toggle when I click on one of the browser rows.
But it only works when there is a single row, when there are several rows it does not find the span and it does not work.
I also tried to use the href to select the correct span, but I don't know how to use it in the JQuery code
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#01" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
<div>
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#02" class='btn btn-default' title='Ver pagos'>
<span class="glyphicon glyphicon-chevron-down"></span>
</a>
</div>
jQuery(function($) {
$('#menu-toggle').on('click', function() {
var $el = $(this),
textNode = this.lastChild;
var $href = $(this).attr('href');
var $href = $href.substring(1);
$el.find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
});```
Try this
var el = 2
for(var i=0; i<el.length; i++) {
document.getElementsByClassName("glyphicon").find('span').toggleClass('glyphicon-
chevron-down glyphicon-chevron-up');
}
Finally I simplified the code so I commented the span and then call with the function onclick CambiaClass, using a class data1, data 2 ... dataN (to identify the item) and now is working fine.
Thanks for your help Rahul!!!
<a id="menu-toggle" data-toggle="collapse" data-parent="#accordion" href="#<?php echo $id_item; ?>"
class='btn btn-default glyphicon glyphicon-chevron-down <?php echo 'dato'.$id_item; ?>'
title='Ver pagos' onclick="CambiaClass('<?php echo 'dato'.$id_item; ?>')">
<!-- span class="glyphicon glyphicon-chevron-down"></span -->
</a>
//Jquery
<script type="text/javascript">
function CambiaClass(idclass) {
$("[class*='"+ idclass+"']").toggleClass('glyphicon glyphicon-chevron-down').toggleClass('glyphicon glyphicon-chevron-up');
}
</script>
I print this buttons with php taking info from the BBDD:
print "
<div class='col-sm-6 col-md-6 col-lg-3 col-xl-3 cartasdos'>
<figure><img class='imagenEditar' height='190px' width='100%' src='../img/relatos/".$fila['imagen']."'></figure>
<h3>".$fila['titulo']."</h3>
<h5>".$fila['autor']."</h5>
<h6 class='resumen'> ".$fila['sinopsis']." </h6>
<a href='index.php?id=".$fila['id']."' class='btn btn-info' role='button'>Editar</a>
<input type='button' class='btn btn-danger borrar ' value='Borrar'>
<a href='crud.php?id=".$fila['id']."' class='btn btn-danger si' role='button'>Borrar</a>
<input type='button' class='btn btn-black cancelar' value='Cancelar'>
</div>";
And then with jquery I want hide and show the buttons separated but when I press one of the buttons it affect to all. This is the jQuery:
<script>
$(document).ready(function(){
$(".si").hide();
$(".cancelar").hide();
var botones=document.querySelectorAll(".borrar");
for(i=0;i<botones.length;i++){
botones[i].addEventListener("click",cancelar,false);
}
});
function cancelar(e){
$(".si").toggle();
$(".cancelar").toggle();
$(e.target).toggle();
$(".cancelar").on("click", function(){
$(".borrar").show();
$(".si").hide();
$(".cancelar").hide();
});
}
</script>
How could I do it?
You can toggle each button with the click() on the selector and toggle() on your button e.g.:
$("selector").click(function(){
$(".yourtBtn").toggle();
});
You want to use $(this) to isolate which item you want to act on. This is an example of the difference:
https://jsfiddle.net/dto07w65/1/
In your case, it might be something like:
<script>
$(function() {
// When you click on any elements with this class
$(".cancelar").on("click", function(){
e.preventDefault();
// Get the parent that wraps this particular clicked element
var parent = $(this).parents('.cartasdos');
// Once selected, show just this element
parent.find(".borrar").show();
// Hide all the others
parent.find(".si").hide();
parent.find(".cancelar").hide();
});
});
</script>
I am not 100% how you want your buttons to work, but his shows how to isolate using $(this).
I finally solve it with an incremented $id, inside of the bucle that print the buttons y write the $id in the principal button and in the rest of buttons I put it in the class:
$id=0;
while($fila=mysqli_fetch_array($res)){
$id++;
print "
<div class='col-sm-6 col-md-6 col-lg-3 col-xl-3 cartasdos'>
<figure><img class='imagenEditar' height='190px' width='100%' src='../img/relatos/".$fila['imagen']."'></figure>
<h3>".$fila['titulo']."</h3>
<h5>".$fila['autor']."</h5>
<h6 class='resumen'> ".$fila['sinopsis']." </h6>
<a href='index.php?id=".$fila['id']."' class='btn btn-info' role='button'>Editar</a>
<input type='button' class='btn btn-danger borrar' id='".$id."' value='Borrar'>
<p class='seguro ".$id."'>Ana, ¿Estás segura?</p>
<a href='crud.php?id=".$fila['id']."' class='btn btn-danger si ".$id."' role='button'>Borrar</a>
<input type='button' class='btn btn-black cancelar ".$id."' value='Cancelar'>
</div>
";
}
And in the jquery code I take the e.target.id for the buttons with the $id in the class and e.target for the principal button with the $id in the id:
<script>
$(document).ready(function(){
$(".seguro").hide();
$(".si").hide();
$(".cancelar").hide();
var botones=document.querySelectorAll(".borrar");
for(i=0;i<botones.length;i++){
botones[i].addEventListener("click",cancelar,false);
}
});
function cancelar(e){
$("."+e.target.id).slideDown('slow');
$(e.target).slideUp('slow');
$(".cancelar").on("click", function(){
$(e.target).slideDown('slow');
$("."+e.target.id).slideUp('slow');
});
}
</script>
I'm fairly new to coding, but have managed to create a function that gets all my elements in the database and echos them out in a list. However, I want each element to have an individual anchorpoint so that i can use the "#" in my link to refer to a specific element.
My whole function currently looks like this (Please excuse some strange names as they're in norwegian):
function visAktiveForslagFlestStemmer()
{
echo "<section id='innhold'><h2>Aktive forslag</h2>";
$db = returnerDB();
if(!$db)
{
die("Kunne ikke knytte til databasen");
}
$sql = "SELECT Tittel, Tekst, COUNT(stemme.ForslagID) AS Antall FROM forslag, stemme WHERE stemme.ForslagID = forslag.ForslagID AND forslag.Aktiv = 1 AND forslag.Besvart IS NULL GROUP BY stemme.ForslagID ORDER BY Antall DESC";
$resultat = $db->query($sql);
$i=1;
$index=1;
while ($rad = mysqli_fetch_array($resultat, MYSQLI_ASSOC))
{
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script>
$(document).ready(function(){
$('#beskrivelse".$index."').hide();
$('#visSkjulButton".$index."').click(function(){
$('#beskrivelse".$index."').toggle(500, 'swing');
});
});
</script>";
if ($i%2==0)
{
$tall="repeteres";
$ftall="forslag";
$sstall="stemmeOgSosialt";
$stall="stemme";
$sotall="sosialt";
}
else
{
$tall="repeteres2";
$ftall="forslag2";
$sstall="stemmeOgSosialt2";
$stall="stemme2";
$sotall="sosialt2";
}
echo "<a id='anchor".$i."'><div class='".$tall."'><div class='".$ftall."'><p><h3>".$rad["Tittel"]."</h3></p><div id='beskrivelse".$index."'>
<p id='forslagbeskrivelse'>".$rad["Tekst"]."</p></div><button class='btn btn-info' id='visSkjulButton".$index."'>Vis/ Skjul</button></div><div class='".$sstall."'><div class='".$stall."'>
<p><div class='btn btn-primary btn-lg center-block disabled'>".antallStemmer($rad["ForslagID"])."</div></p>
<br><br><div class='btn btn-primary btn-lg center-block'>Avgi Stemme</div></div>
<div class='".$sotall."'><a href='http://facebook.com' class='image1'></a><a href='http://twitter.com' class='image2'></a><a href='http://plus.google.com' class='image3'></a>
<div class='btn btn-warning btn-md' id='rapporterButton'>Rapportér</div></div></div></a>";
$i++;
$index++;
}
mysqli_close($db);
This function is called in a separate page, which is included in my index.php-page. My index.php-page also includes a navigation bar, assigning [mywebpage.com/index.php]?page=1 to the end of the url where the function is being called.
The issue I'm having is that adding for example "#anchor1" to this link does not make my browser window jump to the first (or any) element that this function gets from the database.
Can anyone please pont to where my error lies?
In case anyone else has issues wit this, the simple solution was to echo this:
echo "<a id='forslag".$rad["ForslagID"]."'><div class='".$tall."'></a><div class='".$ftall."'><p><h3>".$rad["Tittel"]."</a></h3></p><div id='beskrivelse".$index."'>
<p id='forslagbeskrivelse'>".$rad["Tekst"]."</p></div><button class='btn btn-info' id='visSkjulButton".$index."'>Vis/ Skjul</button></div><div class='".$sstall."'><div class='".$stall."'>
<p><div class='btn btn-primary btn-lg center-block disabled'>".antallStemmer($rad["ForslagID"])."</div></p>
<br><br><div class='btn btn-primary btn-lg center-block'>Avgi Stemme</div></div>
<div class='".$sotall."'>
<a href='https://www.facebook.com/sharer/sharer.php?u=localhost/TestM/index.php?page=1#forslag".$rad["ForslagID"]."' target='_blank' class='image1'></a>
<a href='https://twitter.com/home?status=St%C3%B8tt%20forslaget%20til%20NHHS%20her%3A%20http%3A//localhost/TestM/index.php?page=1%23".$rad["ForslagID"]."' target='_blank' class='image2'></a>
<a href='https://plus.google.com/share?url=nhhs.no' target='_blank' class='image3'></a>
<div class='btn btn-warning btn-md' id='rapporterButton'>Rapportér</button></div></div></div>";
In other words to just surround my first <div> with the anchor point.
Why is it that my onClick won't work?
When I click I get an error message like this:
syntax error : identifier starts immediately after numeric literal
It will not determine the ID from the database, the database ID is varchar(50).
<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate(".$row['affiliateid'].")'></a>
<script type="text/javascript">
function delete_Affiliate(id){
alert(id);
}
</script>
Try this:
delete_Affiliate(" <?php echo $row['affiliateid']; ?>")
That is, you need to echo the value from PHP.
Try this
<script type="text/javascript">
function delete_Affiliate(id){
alert(id);
}
Can you please post your PHP script ?
You should have something like :
<?php
echo "<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate(\"".$row['affiliateid']."\");return false;'></a>
<script type='text/javascript'>
function delete_Affiliate(id){
alert(id);
}
</script>";
?>
try this :
<?php
echo "<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate(".$row['affiliateid'].");'></a>";
?>
or this :
<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate("<?php echo $row['affiliateid'] ?>");'></a>
you have to add php tag and echo statement between your anchor tag like this
<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate("<?php echo $row['affiliateid']; ?>")'></a>
you didn't add this
<?php echo $row['affiliateid']; ?>
in your anchor tag so just add it and check it out.
I hope it will help you
Try this
delete_Affiliate(<?php echo $row['affiliateid']; ?>);
there may be issue on this line
<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate(".$row['affiliateid'].")'></a>
it should be
<a href='#' id='delete' title='Delete' class='icon-2 info-tooltip' onclick='delete_Affiliate("<?php echo $row['affiliateid']; ?>")'></a>
Use this code, hope it will work