console.log return undefined [duplicate] - php

This question already has answers here:
Javascript "this" reference for onclick event not working
(4 answers)
Closed 5 years ago.
<?php
//Load the database configuration file
include 'dbConfig.php';
$sql = "SELECT * FROM users ORDER BY level DESC LIMIT 500";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$i = 0;
while ($row = $result->fetch_assoc()) {
echo '<ul class="list-group">
<li class="list-group-item">
<span class="badge">' . $row['level'] . '</span>
<img id="' . $i . '" onclick="image();" width="30px" height="30px" src="' . $row['picture'] . '"><strong> ' . $row['first_name'] . '
</strong></li>
<script>
function image(this) {
console.log($(this).attr("id"));
}
</script>
';
$i ++;
}
}
?>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
Why is this not working ?
Problem: Console.log is returning undefined.
Why do I get the undefined message? Is there a good way to avoid it?

Check below example. You can achieve it by jquery.
$(document).ready(function(){
$("img").click(function(){
alert($(this).attr("id"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img_123" width="30px" height="30px" src=""><strong>test </strong>

Related

Refresh div contents without closing dropdown

I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.

jQuery loops unexpectedly with PHP

I had an image slider that was working fine with solely html, but now that I have introduced PHP to generate the address for each image from a database, the slideshow loops unexpectedly when it first displays. After this it's fine and the images cycle normally.
Any help?
The result: http://colejohnsontrialsite.com/view.php
My Code:
<script>
$("#slideshow > div:gt(0)").hide();
setInterval(function() {
$('#slideshow > div:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#slideshow');
}, 3000);
</script>
<div id="slideshow" style="float:left;">
<?php
$con=mysqli_connect("localhost","username","pass","database_name");
$result = mysqli_query($con,"SELECT * FROM gifs");
while($row = mysqli_fetch_array($result)) {
echo ' <div> <img id="slideshow" src="' . $row['addresses'] . '">'; echo "</img></div>";
}
mysqli_close($con);
?>
</div>

jquery tabs with mysql and pgp

I am trying to make tabs that contain information about student, these information is stored in the database. I want the first tab to show the information of all students. and the the second tab to show the information of the students that thier grade is A and the the third tab to show the information of the students that thier grade is B.
I made this code but just the first tab shows the information of the students but the second and third tabs don't show anything.
what is wrong with the code?
<html>
<head>
<title>students table</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<?php
$connection = mysql_connect("","","");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $connection);
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
?>
<div id="tabs-1">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
<?Php
$result2 = mysql_query("SELECT * FROM studentTable WHERE grade = 'A'");
while($row = mysql_fetch_array($result2))
{
?>
<div id="tabs-2">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
<?php
$result3 = mysql_query("SELECT * FROM studentTable WHERE grade = 'B'");
while($row = mysql_fetch_array($result3))
{
?>
<div id="tabs-3">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
</div>
</body>
</html>
I think your issue is because you have your tabs-# <div> opening tags inside your while() loops.
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
?>
<div id="tabs-1"> //this here needs to be above/outside while($row = mysql_fetch_array($result)){
This is creating n number of <div id="tabs-1">,<div id="tabs-2">,<div id="tabs-3">, without matching closing tags </div>, so now <div id="tabs-2"> & <div id="tabs-3"> are nested in <div id="tabs-1"> and jQuery doesn't know which one to bind tabs to.
try moving them before the while() loops -
<div id="tabs-1">
<?php
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
...
}
?>
</div>
<div id="tabs-2">
<?php
$result2 = mysql_query("SELECT * FROM studentTable WHERE grade = 'A'");
while($row = mysql_fetch_array($result2))
{
...
}
?>
</div>
<div id="tabs-3">
<?php
$result3 = mysql_query("SELECT * FROM studentTable WHERE grade = 'B'");
while($row = mysql_fetch_array($result3))
{
...
}
?>
</div>
Also, you have echo '</table>'; at the end of each tab div. May want to remove those if you don't actually have a table.
In your script you are trying to use Jquery's tab method.
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
This is looking in the HTML for
<div id='tabs'>
You're tabs in here
</div>
Assuming that your SQL statments is not returing "NULL" then I would say you're issue is that you named you're div's tab-1, tab-2, tab-3. With ID's. This means that Jquery can't find anything to turn into tab's.
Change your jquery call to something like this
<script>
$(function() {
$( ".tabsclass" ).tabs();
});
</script>
and instead of using id's use classes.
<div class='tabsclass' id='tab-1'>
You're tabs in here
</div>
<div class='tabsclass' id='tab-2'>
You're tabs in here
</div>
<div class='tabsclass' id='tab-3'>
You're tabs in here
</div>

.load() little part without toggle

I have a conversations flow who is refresh with .load() of jQuery every 3 seconds.
This system work, but in each conversation I have an answer button who slide a form (textarea and submit button) with .toggle().
To display the flow, I use a while with PHP.
My issue is, when the is loading by .load(), and answer button is clicked, the form hide again and text contain too.
<div id="the_river_loading">
<?php
$sql_the_river = 'SELECT u.nickname, u.firstname, u.lastname, u.main_photo, u.locality,
id_conversation, id_messages, owner, participants, text, date
FROM users AS u
INNER JOIN the_river
ON u.nickname = owner
WHERE answer = 0
ORDER BY date DESC';
$result_the_river = mysqli_query($mysqli, $sql_the_river);
$count = 0;
while ($data_the_river = mysqli_fetch_assoc($result_the_river))
{
$count++;
echo '<div class="message_container_news">'; // Start block conversation
echo '<a href="/profile/' . $nickname . '" class="name_links" style="vertical-align: top; font-size: 16px;">
<img src="' . $main_photo . '" title="' . $name . '" class="members_actu_photo" />' . $name . '</a>
<span style="vertical-align: top">, ' . $locality . '</span><span style="float: right; font-size: 12px;">Posté le Octobre 25, 2012</span>
<p style="margin-top: 5px;">' . $data_the_river['text'] . '</p>
<div class="btnAnswer_nb">' . $count_answer . '</div> Answers
See conversation
<div class="btnAnswer_news" id="btnAnswer_news_id_' . $count . '">Reply</div>
<form method="post" id="display_form_id_' . $count . '" action="" style="display: none;">
<br />
<textarea name="answer_text"></textarea><br />
<input type="submit" name="answer_valid_id_' . $count . '" value="Post" />
</form>
</div>'; // End block conversation
}
?>
</div>
<script type="text/javascript">
$(".btnAnswer_news").live("click", function(){
var num_show = this.id.replace(/\D/g, "");
$("#display_form_id_" + num_show).toggle("fast");
});
var auto_refresh = setInterval(
function() {
$("#the_river_loading").load("/home" + " .message_container_news");
}, 3000
);
</script>
In pleasure of read you.
This is because if you load the content again into the container, the styles applied per js will get removed (because they were applied through style="" and this gets refreshed). You should move the Form and the Button to another Div, wich is not in the loading Div.
If I understand your problem correctly (you've not be very descriptive), you just want to not hide the form when clicking again, for that use show() instead of toggle() , so replace your following line:
$("#display_form_id_" + num_show).toggle("fast");
for this one:
$("#display_form_id_" + num_show).show("fast");
If you want to keep the text of the textarea, you can like so:
var auto_refresh = setInterval(
function() {
tx = $("#the_river_loading textarea[name='answer_text']").val();
$("#the_river_loading").load("/home" + " .message_container_news", function(){
$("#the_river_loading textarea[name='answer_text']").val(tx);
});
}, 3000
);

Looping through a jQuery statement

I'm using a field in one of my databases to store the song location... When I've got 1 song in the db it plays well onClick. But with 2 or more songs in the database, onClick they all play in sync. How do I loop through the jQuery append statement to act like a PHP while loop? Sorry, I'm still learning jQuery/Javascript... I actually run into this problem allot. So a solution would really help me!
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
mysql_connect("localhost", "root", "")or die("Could not connect: " . mysql_error());
mysql_select_db("kevin") or die(mysql_error());
$song_query = mysql_query("SELECT idsongs, songuri, songname FROM songs");
while($row = mysql_fetch_array($song_query)) {
echo "<span class='song'><b>Song Name: </b>";
echo $row['songname'];
echo "<br>";
//echo '<img alt="" id="play" src="play.png" />';
//echo '<div id="audio"></div>';
?>
<script type="text/javascript">
$(document).ready(function() {
$('#play').click(function() {
$("#audio").append('<audio autoplay="true" src="<?php echo $row['songuri'] ?>" /></audio>');
});
});
</script>
<img alt="" id="play" src="play.png" />
<div id="audio"></div>
<?php } ?>
This gives all your songs their own stop/play controls.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
mysql_connect("localhost", "root", "")or die("Could not connect: " . mysql_error());
mysql_select_db("kevin") or die(mysql_error());
$song_query = mysql_query("SELECT idsongs, songuri, songname FROM songs");
while($row = mysql_fetch_array($song_query)) {
echo "<div class='song' sid='".$row['idsongs']."' songuri='".$row['songuri']."'>";
echo "<b>Song Name: </b>";
echo $row['songname'];
echo "<br>";
echo "<img class='play' src='play.png' /><br>";
echo "<div class='audio'></div>";
echo "<div class='stop'>Stop!</div>";
echo "</div>";
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.play').click(function() {
var songdiv = $(this).parent('div.song');
var songuri = songdiv.attr('songuri');
var sid = songdiv.attr('sid');
// stop this song if it's already playing
stopPlayer(sid);
// play
var audio = '<audio class="player" sid="'+sid+'" autoplay="true" src="'+songuri+'" /></audio>';
$(this).siblings('div.audio').html(audio);
});
$('.stop').click(function(){
var songuri = $(this).parent('div.song').attr('sid');
stopPlayer(songuri);
});
});
function stopPlayer(id) {
var p = $('.player[sid='+id+']');
if (p[0]) {
p[0].pause();
}
}
</script>
It appears to me that you've provided no mechanism to append your autoplay=true to the specific play button that was clicked -- you're appending it to all elements with #audio. Try generating unique ids for every play and div with audio so you can link the two together.
As a first stab, try this:
while($row = mysql_fetch_array($song_query)) {
echo "<span class='song'><b>Song Name: </b>";
echo $row['songname'];
echo "<br>";
echo '<img alt="" id="' + "play-$row[idsongs]" + '" src="play.png" />';
echo '<div id="' + "audio-$row[idsongs]" +'"></div>';
This gives you unique identifiers for all your objects; I don't know JS well enough to suggest how to correlate the audio-$row[idsongs] when a play-$row[idsongs] has been clicked, but surely there must be some way to discover the id of the clicked object, change play to audio, and then append the HTML.

Categories