In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.
I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.
(To simplify the example code, I left out the AJAX part and am using an alert instead.)
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var shelve = document.getElementById( 'books' );
var books = shelve.getElementsByTagName( 'li' );
for( var i=0; i < books.length; i++ ){
books[i].onclick = function(){
alert(books[i].title); //I know this doesn't work
};
}
}
</script>
</head>
<body>
<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>
<?php show_allBooks(); ?>
</body>
</html>
<?php
function show_allBooks(){
db_connect();
$query = "Select * from tblBooks order by title";
$result = mysql_query($query);
echo "<ul id='books'>";
while ($row = mysql_fetch_array($result))
{
echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
}
echo "</ul>";
db_close();
}
?>
I tried fooling around with variations of the following code, but this did not seem to work either.
books[i].getAttribute("title")
Can anyone point me in the right direction? Any help would be greatly appreciated.
By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = function () {
alert(this.title);
};
}
http://jsfiddle.net/gilly3/cPMAU/
However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:
function createBookHandler(books, i) {
return function() {
alert(books[i].title);
};
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = createBookHandler(books, i);
}
http://jsfiddle.net/gilly3/cPMAU/1/
Start with
books.item(i)
Then it depends how title is stored in the list. If its
<li title="">
then
books.item(i).getAttribute("title")
But the closure related answer is probably more important.
Related
I have coded the two HTML pages below.
Page2d.php is intended to display a select element that allows the client to select an ID, then open a new window with that ID showing on a new page (Page3b.php) when the button is clicked. The parent (Page2d.php) keeps an array of child windows globally.
Problem 1: ID number selected did not write to child window.
Because the script is malfunctioning I receive an error in the Google console stating "Uncaught TypeError: Cannot set property 'innerHTML' of null".
I am using an array of IDs to record those selected and I realize this might not be the best idea but I tried so many different ways with no success. Help !!!!
Page2d.php
<!doctype html>
<html>
<head>
<title>Page 2d</title>
<script type='text/javascript'>
var IDS = [];
var WindowTabs = 0;
var WindowRef = [];
function TestIfOpen() {
var OkToOpen = 1; //true
//Get the ID selected
var sel = document.getElementById('_ID');
var opt = sel.options[sel.selectedIndex];
var IDselected = opt.value;
if (WindowRef.length == 0) {
IDS[WindowTabs] = IDselected;
WindowRef[WindowTabs] = window.open('Page3b.php?TAB=' + WindowTabs, '');
WindowRef[WindowTabs].document.getElementById('_ID').innerHTML = "ID equals " + IDselected;
} else {
for (var x = 0; x < WindowRef.length; x++) {
if(!WindowRef[x].closed) {
if(IDS[x] == IDselected) {
OkToOpen = 0; //false
alert("A window for this ID is already opened");
}
} else {
IDS[x] = 0;
}
}
if (OkToOpen == 1) {
WindowTabs++;
IDS[WindowTabs] = IDselected;
WindowRef[WindowTabs] = window.open('Page3b.php?TAB=' + WindowTabs, '');
WindowRef[WindowTabs].document.getElementById('_ID').innerHTML = "ID equals " + IDselected;
}
}
}
</script>
</head>
<body>
<?php
echo "<form method='POST' action='$PHP_SELF'>";
$IDS = array("200","201","202","203","204","205","206");
echo "Select an ID:<p><select name='_ID' id='_ID'>";
foreach($IDS as $value) {
echo "<option value='".$value."'";
if($value == $_POST['_ID']) {
echo " selected ";
}
echo ">".$value."</option>";
}
echo "</select></p>";
echo "<button type='button' onclick='TestIfOpen();'>Click Here to Open a window for this ID</button></form>";
?>
</body>
</html>
Page3b.php
<!doctype html>
<html>
<head>
<title>Page 3b</title>
</head>
<body>
<span id='_ID'>This is original text</span><br>
</body>
</html>
P.S.
My original post contained errors in array management that I discovered and have repaired in the code above.
I'm making an API where I would like to get all users and then display them in some sort of table. However now I'm getting a ReferenceError: $output is not defined when running the code. I tried this out in another project and it doesn't give that error there.
My JavaScript code:
function displayData(data) {
$('.content').empty();
console.log(data.length);
for (var i = 0; i < data.length; i++) {
$output += '<div>' + data[i].ContactName + '</div>';
$(".content").append($output);
}
}
Which I'm trying to output to this div:
<div class="content">
</div>
I have no idea why I am getting this error while it is running without on another project. Thanks in advance for helping me out!
Please Refer Below Fiddle..
Fiddle
JavaScript
var $output = '';
var data = [{'ContactName':'ABC'},{'ContactName':'EFG'}]
$( document ).ready(function() {
displayData(data);
});
function displayData(data){
$('.content').empty();
console.log(data.length);
for (var i = 0; i<data.length; i++) {
$output+= '<div>'+data[i].ContactName+'</div>';
$(".content").append($output);
}
}
HTML
<div class="content">
</div>
Declare $output as a Variable.
var $output = '';
when i try dd($conv) the data are there, but I still can't display them inside the script.
Anyone know whats the problem, I have tried many ways but they doesn't seem to work.
<h4>{{$row->transcript_text}}</h4>
<?php $conv = json_encode($row->transcript_text); ?>
<script type="text/javascript">
function splitArray() {
var myStr = <?php echo $conv; ?>;
var strArray = myStr.split(/(?= \| \d)/);
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
})
}
splitArray();
</script>
I don't know which version of Laravel you're using but the recommended way to embed plain PHP in your HTML templates is with the #php notation (cf doc).
Anyway, that's something I'd try to avoid. Instead, Laravel blade has native ways of doing what you're trying to do.
#if(! empty($history))
#foreach($history as $row)
<script type="text/javascript">
function splitArray() {
var myStr = JSON.parse("{{json_encode($row->transcript_text) }}");
var strArray = myStr.split(" | 0");
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
}
}
</script>
<body onload="splitArray()" style="color: lime">
</body>
#endforeach
i have been scrolling for a solution for ages now and i cant seem to make it work.
i am trying to make some sort of library where u can hover on an icon while hovering it displays that image into image tag. as you can see from the image below my php statement returned 2 images at the left. and while hovering i want the hovered image to display in the big img tag. but hovering is not working.
Here is my javascript
<script type="text/javascript">
//imageview
$(document).ready(function loading(){
var getimg = document.getElementById("icoimg").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
});
</script>
And here is my php mysqli while loop
$count = 1;
if($count <= 6){
while($row = mysqli_fetch_array( $query )) {
$imgcase = $row['Showcase_Image'];
$itemname = $row['Product_Name'];
$itemid = $row['Product_ID'];
echo "<div class='imgico' id='imgico'><img id='icoimg' name='icoimg' src=$imgcase onmouseover='loading();' /></div></br>";
$count++;
}
}
and this is the big img preview
<div class="imgprev" id="imgprev" width="460" height="300"><img id="selectedimg" width="460" height="300" /></div>
I have tried numerous tricks i tried inventing my own code. I searched all over the net but no luck. What i am thinking is MAYBE because the generated id's inside the tags have the same ID that maybe my img hover is useless. Maybe i need to find a way to get each generated id tags a unique id and call and then call that tag's id which should be "unique" in javascript and then apply the function? if so how?
Any lifesaver that can help me? Thx in advance!
Php and Javascript only..no CSS plz(unless its the only hope...lol)
EDIT: I did a "Hardcoding" and it worked but even tho its hardcoded i dont want it to work like this.I want to display max 5 images which is why i have a count function before my while loop in my php code. but if i cant find a better way i think im just going to stick with this unprofessional hardscript lol
if($count <= 6){
while($row = mysqli_fetch_array( $query )) {
$imgcase = $row['Showcase_Image'];
$itemname = $row['Product_Name'];
$itemid = $row['Product_ID'];
echo "<div class='imgico' id='imgico'><img id=$count name='icoimg' src=$imgcase onmouseover='loading$count();' /></div></br>";
$count++;
function loading1(){
var getimg = document.getElementById("1").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading2(){
var getimg = document.getElementById("2").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading3(){
var getimg = document.getElementById("3").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading4(){
var getimg = document.getElementById("4").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
function loading5(){
var getimg = document.getElementById("5").getAttribute("src");
document.getElementById("selectedimg").src = getimg;
};
echo "<div class='imgico'><img name='icoimg' src=$imgcase onmouseover='loading(this);' /></div></br>";
You can't use the id as the selector to get the img, because it is supposed to be unique.
Instead, in your javascript, you can pass a reference to the element that called the loading() function :
echo "<div class='imgico'><img name='icoimg' src=$imgcase onmouseover='loading(this);' /></div></br>";
<script type="text/javascript">
//imageview
$(document).ready(function loading(elm){
var getimg = elm.getAttribute("src");
document.getElementById("selectedimg").src = getimg;
});
</script>
Well my page works now.
The answer i received from Galcha was the first thing i ever used so it didnt really help. after some thinking i decided to replace $(document).ready(function loading(elm) with function loading(elm) . So my script looks like this now
function loading(elm){
var getimg = elm.getAttribute("src");
document.getElementById("selectedimg").src = getimg;
}
Now after using this the hover works perfect. BUT it does not auto display the first image on page load. So i modified my while statement a bit and now it looks like this.
$count = 1;
if($count <= 6){
while($row = mysqli_fetch_array( $query )) {
$imgcase = $row['Showcase_Image'];
$itemname = $row['Product_Name'];
$itemid = $row['Product_ID'];
echo "<div class='imgico'><img name='icoimg' src=$imgcase onmouseover='loading(this);' /></div></br>";
if($count <= 1){
$imgfirst = $imgcase;
}
$count++;
}
}
Now my page works perfectly. Incase you ask why i have a count <1 statement in my while loop?
Because if i just echo the $imgcase in the selectedimg src code i will get the last image src autodisplayed. And i wanted the first one. Thats why i made a count <=1 to get the first link and give the first link a seperate variable and echo's $imgfirst in the selectedimg src.
My code is a bit scrappy but...it works i guess lol.
I want to paginate results obtained thusly:
function processResponse(response){
var myObj = JSON.parse(response);
var weighInData = myObj["WEIGH-INS"];
var weights = []; // re: weigh-in count and calculating highest/lowest
var userDisplayEl1 = document.getElementById("user-display-weigh-in-data");
var weighInCountEl = document.getElementById("weigh-in-count");
var weightLowEl = document.getElementById("weight-low");
var weightHighEl = document.getElementById("weight-high");
var weightgoalEl = document.getElementById("weight-goal");
var dataRows = document.getElementById("data-rows");
userDisplayEl1.innerHTML = "";
weighInCountEl.innerHTML = "";
weightLowEl.innerHTML = "";
weightHighEl.innerHTML = "";
weightgoalEl.innerHTML = "";
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) {
weights.push(weighInData[obj].weight);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
dataRows.innerHTML += row;
// pagination here?
} // if ... === selUser
} // for var obj in weighInData
var weighInCount = weights.length;
var weightLowest = Math.min.apply(null, weights);
var weightHighest = Math.max.apply(null, weights);
userDisplayEl1.innerHTML = weighInData[obj].user + "'s weigh-ins:";
weightLowEl.innerHTML += weightLowest;
weightHighEl.innerHTML += weightHighest;
weighInCountEl.innerHTML = weighInCount;
} // processResponse
It seems that, because I'm executing Math on the results (after the for loop), I cannot use a limit in my db query, else the math would be inaccurate (executing only on the chunks of data, and not on the entirety of the data). So it seems I'll have to paginate on the client, but I have no idea how to proceed given how I'm currently loading/displaying the data. I have looked briefly at a couple of pagination plugins but since I wasn't clear on how to implement them given my extant code, I prefer the learning curve of achieving this w/out a plugin (or jQuery).
Any suggestions/pushes in the right direction, with the assumption that I con't substantively alter what I have now (which works, and which I understand, will be most appreciated.
Btw, my server-side code, fwiw:
$table = "`WEIGH_IN_DATA`";
if ($mysqli) {
$user = $_GET['selUser'];
$i = 0;
$jsonData = '{"WEIGH-INS": [';
$stmt = $mysqli->stmt_init();
$query = "SELECT * FROM $table WHERE USER = '$user'";
$result = $mysqli->query($query) or die("Error in the query (?)" . mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)) {
$i++;
$user = $row["USER"];
$date = $row["DATE"];
$weight = $row["WEIGHT"];
$jsonData .= '{"user": "'.$user.'", "date": "'.$date.'", "weight": "'.$weight.'" },';
}
$jsonData = chop($jsonData, ","); // kill the trailing comma
$jsonData .=']}';
echo $jsonData;
}
Thank you,
svs
To save time, using a plug-in might be your best bet. I'm sure there are tutorials on building your own pagination plug-in on the internet which you can google.
I picked a random jQuery pagination plug-in (datatables), appended some data via js (similar to your code), then called the plug-in on the result table. Something like this may/may not work for you. Also, this is dependent on jQuery, and I'm not sure if you can include this library or not on your website.
Here's an example using dataset and jquery: http://codepen.io/anon/pen/IbBxf
Link to datatables: http://www.datatables.net/
$(document).ready(function(){
// append some data to an existing table in the DOM
for (var i =0 ; i < 10; i++) {
var $nr = $('<tr><td>A-' + i + '</td><td>B-' + i + '</td></tr>');
$('#myTable').append($nr);
}
// after table is populated, initiate plug-in and point to table
$('#myTable').DataTable(
{ "lengthMenu": [[5, 10, -1], [5, 10, "All"]] });
});
If you can't use jQuery:
Vanilla JS: It looks like this library can do pagination, however you'll need to read through the docs:
http://listjs.com/docs/plugins/pagination
This link also looks promising for your case (vanilla JS only):
http://www.tekgarner.com/simple-pagination-using-javascript/
HTML/CSS: If you don't need a lot of features, maybe you could also look at just adding a scrollbar to your HTML table results.
How to display scroll bar onto a html table