JSON data pass to div tag - javascript

I have the following code and it won't work. I want to pass the JSON data to the HTML div tag through javascript.
This is a div tags what I want to import data
<div class="row mt-2 mb-2 height bg-dark text-light" id="<?php echo $row['dev_ID']; ?>">
<div class="col-3" >
<div class="card height bg-dark" style="width: auto">
<div class="card-body" >
<h6 id="trname">Name : </h6>
<p id="trtype"></p>
</div>
</div>
</div>
<div class="col-2">
<div class="card height bg-dark" style="width: auto">
<div class="card-body">
<h6>Status</h6>
<p ><p id="trstatus"></p><?php // echo $row['dev_Status']; ?></p>
</div>
</div>
</div>
<div class="col-3">
<div class="card height bg-dark" style="width: auto">
<div class="card-body">
<h6>Reading 01</h6>
<p id="trreading01"><?php// echo $row['dev_Reading01']; ?></p>
</div>
</div>
</div>
<div class="col-3">
<div class="card height bg-dark" style="width: auto">
<div class="card-body">
<h6>Reading 02</h6>
<p id="trreading02"><?php// echo $row['dev_Reading02']; ?></p>
</div>
</div>
</div>
<div class="col-1">
<div class="card height bg-dark" style="width: auto">
<div class="card-body">
<h6>Dev</h6>
</div>
</div>
</div>
</div>
This is my javascript part. I'm guessing I'll need to use AJAX or Jquery but I lack the knowledge on how to do so.
document.getElementById('button').addEventListener('click',loadReadings);
//load readings
function loadReadings(){
setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open('POST','xhr.php',true);
xhr.onload = function(){
if(this.status == 200){
var obj =this.responseText;
console.log(this.responseText);
for (var key in obj){
if(obj.hasOwnProperty(key)){
var row = document.getElementById(obj[key].id);
// innerHTML = property is useful for getting or replacing the content of HTML elements.
row.div[1].innerHTML = obj[key].dev_type;
row.trstatus[2].innerHTML = obj[key].status;
row.trreading01[3].innerHTML = obj[key].reading01;
row.trreading02[4].innerHTML = obj[key].reading02;
}
}
}
}
xhr.send( )
},1000);
}
and also this is the php part.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb1";
$array = array();
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM dmaster";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$arraynew = array(
'id' =>$row["dID"],
'dev_name' =>$row["dName"],
'dev_type' =>$row["dType"],
'access_code' =>$row["access_Code"],
'time_stamp'=>$row["time_Stamp"],
'status' =>$row["dStatus"],
'reading01' =>$row["dReading01"],
'reading02' =>$row["dReading02"]
);
$arraynew = array_map('htmlentities',$arraynew);
array_push($array,$arraynew);
}
} else {
//echo "0 results";
}
mysqli_close($conn);
$json = html_entity_decode(json_encode($array));
echo "data: ".$json."\n\n";
ob_end_flush();
flush();
?>

As i checked your code and found some of the issue kindly update
update in php file:
echo "data: ".$json."\n\n";
replace with only echo $json;
Update in javascript script:
<script type="text/javascript">
function loadReadings(){
var xhr = null;
if(window.ActiveXObject) { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
else if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }
if(xhr)
{
xhr.open('POST','xhr.php',true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var obj = JSON.parse(xhr.responseText);
for (var key in obj){
if(obj.hasOwnProperty(key)){
var row = document.getElementById(obj[key].id);
console.log(row);
// innerHTML = property is useful for getting or replacing the content of HTML elements.
row.getElementsByTagName('div')[1].innerHTML = obj[key].dev_type;
document.getElementById('trstatus').innerHTML = obj[key].status;
document.getElementById('trreading01').innerHTML = obj[key].reading01;
document.getElementById('trreading02').innerHTML = obj[key].reading02;
}
}
}
}
xhr.send();
}
}
</script>
Because in your script checked only by xhr status not readystate hence it will create issue when ajax request will fire , and one more thing you set the value by taking the reference of row var it okay for div but remaining all how already id so no need to take any of reference but if you are thinking , you may list multiple of dynamic info then define all to a class because by your current code ,your page will contain multiple of same ids which is not right
update in html:
as you bind a event with button id by you do not any button id to any of the tag
So add this line on your html code
<button type="button" onclick="loadReadings()">Click here </button>

Related

How to print all elements by id (JS,PHP)

I have some list from db using foreach, and now i would like to when i press button print to print all elements with "print" id, but in my case when i click print i only can print first item in list, not all.
<?php $unos = $db->odradi("SELECT * FROM books WHERE cust='$cust' ORDER BY id ASC");
if (!empty($unos)) {
foreach($unos as $podatak=>$value){
$r_id=$unos[$data]['id'];
?>
<div class="col-xs-12 col-sm-4 col-lg-2" id="print">
<div class="well well-sm bg-color-light txt-color-black text-center">
<small><?php echo $db[$data]['name'] ?></small><br>
<img alt="<?php echo $unos[$data]['name'] ?>" src="barcode.php?codetype=Code39&size=40&text=<?php echo
$unos[$data]['id'] ?>&print=true" />
</div> </div> <?php }
} ?>
<button onclick="printaj()">Print all</button>
And my JS:
<script>
function printaj() {
var prtContent = document.getElementById("print");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
</script>
id's in HTML must be unique - you create multiple id=print and document.getElementById will return a single element
If it returned multiple elements, your code would still fail, since your code relies on the fact that document.getElementById returns a single element!
So, I'd suggest a single outer div with id=print as follows
<?php
$unos = $db->odradi("SELECT * FROM books WHERE cust='$cust' ORDER BY id ASC");
if (!empty($unos)) {
?>
<div id="print">
<?php
foreach($unos as $podatak=>$value){
$r_id=$unos[$data]['id'];
?>
<div class="col-xs-12 col-sm-4 col-lg-2">
<div class="well well-sm bg-color-light txt-color-black text-center">
<small><?php echo $db[$data]['name'] ?></small><br>
<img alt="<?php echo $unos[$data]['name'] ?>" src="barcode.php?codetype=Code39&size=40&text=<?php echo $unos[$data]['id'] ?>&print=true" />
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
<button onclick="printaj()">Print all</button>
With this solution, printaj does not need to be changed
Solution 1: use class name instead of ID and itterate through class objects:
function printaj() {
var prtContent ;
var content= document.getElementsByClassName("print");
for(var i = 0; i < content.length; i++)
{
prtContent =prtContent +content(i).innerHTML;
}
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
solution 2:
wrap all generated content inside a single div with id="print" and print it!

Content of innerHTML is "undefined"

I never had this problem before, but now working with PHP when I try to edit the content of a div with the id of a product taken directly from it's id in the database like this (both separaed in two foreach getting their current correct IDs) because I need them separated so when I can change the content, I can modify it so I can make the second DIV display: none by default and after clicking the first one making it display: inline:
<div id="h<?php echo $obra['id'] ?>" onClick="display()"> </div> // Getting ID h + 84 (h84) this time
<div id="<?php echo $obra['id'] ?>"> TEST TEXT</div> // Getting ID 84 this time)
And the function is:
function display() {
var result = document.getElementById("84").innerHTML;
result.innerHTML = "test";
alert(result);
}
Now, when I click the first DIV, it should get the content of the div with ID 84, which is "TEST TEXT", and then change it for "test" and change the content which I see in the browser and after that, alert with the new result value, but the content doesn't change and the alert shows me TEST TEXT.
Here is the full relevant code if needed:
<div class="row m-0">
<div class="accordion pl-0 col-4 text-center">
<?php if ( count($cuadros) == 0) { ?>
<p class="text-center mt-3">No hay cuadros registrados.</p>
<?php } else {
$cont = 0;
foreach ( $cuadros as $obra ) { ?>
<div class="card border-top-0 border-left-0 rounded-0 p-0">
<div class="card-header border-0" id="h<?php echo $obra['id'] /* it gets value "84" */ ?>" onClick="display()">
<h5 class="mb-0">
<?php echo $obra['nombreObras']; ?>
</h5>
</div>
</div>
<?php $cont++; } ?>
</div>
<?php foreach ( $cuadros as $obra ) { ?>
<div class="col-4 hidden" id="<?php echo $obra['id'] /* It gets value "84" */ ?>">
TEST TEXT
</div>
<?php } ?>
<?php } ?>
</div>
And a screenshot of what happens (note that the change should be reflected in the alert, which is not)
Thank you!
You are performing innerHTML agin. So it will return error. Remove innerHTML from result
function display() {
var result = document.getElementById("84");
result.innerHTML = "test";
alert(result);
}

Angular JS duplicates not showing any data

The result I want is the product details uploading from the database once the data is fetched. It shows the error of duplicate entries.
angular.min.js:107 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.4.8/ngRepeat/dupes?p0=products%20in%20data&p1=string%3An&p2=n
at Error (native)
I have two enteries in the database but I can't find the problem.
HTML
<html ng-app="fetch">
<head>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="listproduct.css">
<!-- jQuery library -->
<script src="jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="angularscript.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Ladies Boutique</a>
</div>
</div>
</nav>
<div class="container">
<div class="row " ng-controller="dbCtrl">
<div class="item col-xs-4 col-lg-4 " ng-repeat="products in data" >
<div class="thumbnail" >
<img class="group image" src=""{{products.PRODUCT_IMAGE_LINK}}"" alt="" />
<div class="caption">
<h4 class="group inner item-heading">{{products.PRODUCT_NAME}}</h4>
<p class="group inner item-text">{{products.PRODUCT_DESCRIPTION}}</p>
<div class="row">
<div class="col-xs-12 col-md-6">
<p class="lead">
&#8377 {{products.PRODUCT_PRICE}}</p>
</div>
<div class="col-xs-12 col-md-6">
<a class="btn btn-success" href="#">Add to cart</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
listproduct.php
<?php
// Including database connections
$database='angulardatabase';
$connection= mysqli_connect('localhost', 'root', '');
if(!$connection){
die("Database Connection Failed".mysqli_errno($connection));
}
else
{
echo'Connection Successfull';
}
$select_db= mysqli_select_db($connection, $database);
if(!$select_db)
{
die("Database Selection Failed".mysqli_errno($connection));
}
// mysqli query to fetch all data from database
$query = "SELECT * from angulartable";
$result = mysqli_query($connection, $query);
$data = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
// Return json array containing data from the databasecon
echo $json_info = json_encode($data);
?>
angularscript.js
var fetch = angular.module('fetch',[]);
fetch.controller('dbCtrl',['$scope','$http',function($scope,$http){
$http.get("exactphp.php")
.success(function(data){
$scope.data=data;
alert(data);
})
.error(function(){
$scope.data="error in fetching data";
alert("Error in fetching data");
});
}]);
listproducts.css
.glyphicon { margin-right:5px; }
.thumbnail
{
margin-bottom: 20px;
padding: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
}
.item.list-group-item
{
float: none;
width: 100%;
background-color: #fff;
margin-bottom: 10px;
}
.item.list-group-item:nth-of-type(odd):hover,.item.list-group-item:hover
{
background: #428bca;
}
.item.list-group-item .list-group-image
{
margin-right: 10px;
}
.item.list-group-item .thumbnail
{
margin-bottom: 0px;
}
.item.list-group-item .caption
{
padding: 9px 9px 0px 9px;
}
.item.list-group-item:nth-of-type(odd)
{
background: #eeeeee;
}
.item.list-group-item:before, .item.list-group-item:after
{
display: table;
content: " ";
}
.item.list-group-item img
{
float: left;
}
.item.list-group-item:after
{
clear: both;
}
.list-group-item-text
{
margin: 0 0 11px;
}
body
{
background-color: white;
padding-top:80px;
}
Use track by index
ng-repeat="products in data track by $index"
It track by $index keeps track of each object in the data array separately based on index of each item in the array. So, even if there are duplicates in the data ng-repeat can keep track of them separately.
Occurs if there are duplicate keys in an ngRepeat expression. Duplicate keys are banned because AngularJS uses keys to associate DOM nodes with items.
The message tells you exactly what to do:
Use 'track by' expression to specify unique keys
If you have identifier such as unique ID (for example products.id use track by products.id). If you don't, use $index due the $index is always unique.
You are getting this error because your data have some duplicates keys. So to remove this just use track by $index.
Hence you modified code:
<div class="item col-xs-4 col-lg-4 " ng-repeat="products in data track by $index" >
<div class="thumbnail" >
<img class="group image" src=""{{products.PRODUCT_IMAGE_LINK}}"" alt="" />
<div class="caption">
<h4 class="group inner item-heading">{{products.PRODUCT_NAME}}</h4>
<p class="group inner item-text">{{products.PRODUCT_DESCRIPTION}}</p>
<div class="row">
<div class="col-xs-12 col-md-6">
<p class="lead">
&#8377 {{products.PRODUCT_PRICE}}</p>
</div>
<div class="col-xs-12 col-md-6">
<a class="btn btn-success" href="#">Add to cart</a>
</div>
</div>
</div>
</div>
</div>
Its Done and it was mistake from my side in the listproduct.php file .
<?php
// Including database connections
$database='angularwaladatabase';
$connection= mysqli_connect('localhost', 'root', '');
if(!$connection){
die("Database Connection Failed".mysqli_errno($connection));
}
else
{
echo'Connection Successfull';
}
$select_db= mysqli_select_db($connection, $database);
if(!$select_db)
{
die("Database Selection Failed".mysqli_errno($connection));
}
// mysqli query to fetch all data from database
$query = "SELECT * from angularwalatable";
$result = mysqli_query($connection, $query);
$data = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
// Return json array containing data from the databasecon
echo $json_info = json_encode($data);
?>
The mistake is that json data was taking that "connection successfull" of the if else statement in the JSON and angular was getting confusing of that.
<?php
// Including database connections
$database='angularwaladatabase';
$connection= mysqli_connect('localhost', 'root', '');
$select_db= mysqli_select_db($connection, $database);
if(!$select_db)
{
die("Database Selection Failed".mysqli_errno($connection));
}
// mysqli query to fetch all data from database
$query = "SELECT * from angularwalatable";
$result = mysqli_query($connection, $query);
$data = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
// Return json array containing data from the databasecon
echo $json_info = json_encode($data);
?>
Thanks You All . Thanks for making me correct and you were right and correct . Thanks a Lot !!

mysql retrieve data, for each data append a new row

i'm doing a project for my school whereby i have to retrieve student works from database.
On my home page, i have preset 10 div to hold the data returned from query. I preset it because i only need to retrieve 10 data.
HTML
<div class="viewport-computer col-lg-12 visible-lg no-padding ">
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
</div>
Then i use jquery to query to my php to get back 10 data and place onto my 10 div
Jquery
/* Home Page Autoload featured thumbnails based on computer viewport/mobile viewport
================================================== */
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/displayFeatThumbs.php",
success: function(data) {
// Display image thumbnail, caption & description of works onto each thumbnail div
$('.viewport-computer .img_thumb_holder img').each(function(index, element) {
// Work out the data to set
var imageUrl = "cms/" + data[index].links;
var captionHtml = "<span>" + data[index].caption + "<span class='spacer'></span><br/><span class='spacer'></span>" + data[index].title + "</span>"
// Now apply this to the elements
$(element).attr("src", imageUrl); // i must find a way to solve this
$(element).parent().css('background-image', 'url("'+imageUrl+'")');
$(element).next().html(captionHtml);
// push the caption & id into global variable array to be used on other functions easily
captionArray.push(data[index].caption);
idArray.push(data[index].id);
homeLinksArray.push(data[index].links);
homeTitleArray.push(data[index].title);
});
});
It's working fine since i loop through my preset div(10 of them) and then place the data into each div.. Now i need to do a search bar function, and it will return me ALL the results(more than 50), and i have to display all of them, now the problem is that i only preset 10divs, so my workflow is not good for this
so instead of my current
loop through 10 div > retrieve data and place on 10 div
i would like to
retrieve all data, for each data, append a new div and place it
i am not very good with php as i'm still a new learner so i'm stuck at this although i have the idea on how to do it. Can someone enlighten me on how i can loop through each data and append instead of my preset divs?
PHP
<?php
include 'dbAuthen.php';
$searchBar = $_POST['searchBar'];
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div>hi</div>',
$links[] = array(
"id" => $row["UserID"],
"links" => $row["Link"],
"caption" => $row["Name"],
"title" => $row["Title"],
);
}
//shuffle($links);
echo json_encode($links);
} else {
echo "0 results";
}
?>
Solution is not to preset 50 divs or 10 divs in your UI.
Simply when you retrieve your result loop through all records and at the same time instead of populating your divs you create divs on the fly and insert data to it. When newly created divs are ready append them to your UI with some classes like 'new-data' or something to give a look that these records are somewhat new in your UI.
Assuming data represent your json returned by PHP and data is collection of all records here is one way to do it
for(i=0; i<data.length; i++)
{
$('<div class="col-lg-2 img_thumb_holder no-padding new-class">'
+'<img src="'+data[i].imgSrc+'" class="img_thumb">'
+'<h2 class="caption">'+data[i].author+'<br />'+data[i].description+'</h2>'
+'</div>').appendTo("ul#yourRecordHolderElemenet").slideDown("fast");
}
Exact solution might depend on your json returned by PHP untill you show your exact json response we won't be able to help you properly.
I won't recommend returning data with their html markup being returned from PHP as it would increase amount of data being transferred.
Since you already have the information in database, add them directly in HTML rather than making a ajax request.
<div class="viewport-computer col-lg-12 visible-lg no-padding ">
<?php
//You can get 10 records from database using 'limit 10' added to select query.
//Get data from database. I assume you have the data in a variable $datafromdb
foreach($datafromdb as $data){
?>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption"><?=$data['author']?><br /><?=$data['description']?></h2>
</div>
<?php } ?>
</div>
Without writing complete code for you here is a step by step how you could do this
Create a database connection with mysqli or pdo
Select all records with a select query
Do a foreach on the resultset
Add one div in the foreach
PHP will add a div for each row in the select query
for example:
foreach($result->fetch_array() as $row) {
?>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption"><?= $row['author'] ?><br /><?= $row['description'] ?></h2>
</div>
<?php
}
PHP Code should be :
<?php
include 'dbAuthen.php';
$searchBar = $_POST['searchBar'];
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div>hi</div>',
$links = array(
"id" => $row["UserID"],
"links" => $row["Link"],
"caption" => $row["Name"],
"title" => $row["Title"],
);
}
//shuffle($links);
echo json_encode(array('contents' => $links));
} else {
echo "0 results";
}
?>
notice single dimension $link array and an associative array to json_encode.
In jQuery, your success: can/will be :
success: function(data){
$.each(data.contents, function(ind, ele){
// ele.id is the id and etc... or ind.id. :D
});
}

jquery .attr() returning as undefined

I have the following jQuery code below:
My Html:
<div class="input-group top_buffer_small">
<label class="col-md-3 col-sm-3 text_right top_buffer_mini">Available Colors:</label>
<div class="col-md-9 col-sm-9 text_right">
<table id="availColors" align="center">
<?php
//instantiate color class
$colors = $Item->getColors();
$colorCount = $Item->getColorCount();
if($colorCount > 0){
//create a mod since we only want to show 4 colors per row.
$remainder = $colorCount%4;
$x=0; //counter variable
if(is_array($colors)){
foreach ($colors as $key=>$value){
foreach ($value as $color) {
if($remainder == 0){
//if we are at 0, make a new row
echo "<tr>";
}
//print_r($Item->getProductVariations($color));
?>
<td style="background-color:#<?php echo $color;?>" data-pictures="<?php echo htmlspecialchars(json_encode($Item->getProductVariations($color))); ?>" data-directory="<?php echo $pictures.$category.'/'.$itemid.'_'.$itemName.'/';?>"></td>
<?php
if($remainder == 3){
//end the row
echo "</tr>";
}
//$x++;
}
}
}
}
?>
</table>
</div>
</div>
Basically, I am trying to get the array values which are being passed from the to my javascript. After I get the values, I am trying to make all the image thumbnails change to the pictures on click of a color.
This is the div I am aiming to change the picture thumbnails:
<div class="row">
<div class="featured_container_small" id="productThumbnails">
<h5>Other Views</h5>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<!-- <div class="col-md-3 buffer_bottom"><img src="<?php echo $pictures.$category.'/'.$itemid.'_'.$itemName.'/'.$smallimage1?>" class=" center_image responsive_image"></div> -->
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
</div>
<div class="row">
<div class="col-md-12"><nbsp></nbsp></div>
</div>
<div class="clear"></div>
</div>
Then this is my jquery:
$(function(){
$("#availColors td").click(function(){
var imageDirectory = $(this).attr('data-directory');
var pictures = $(this).attr('data-pictures');
var pictureArray = JSON.parse(pictures);
var productThumbnails = $("#productThumbnails img");
var thumbnailCount = productThumbnails.length;
var keys = Object.keys(pictureArray);
var pic = "";
var src="";
for (var i = 0; i < keys.length; i++) {
pic = pictureArray[keys[i]];
productThumbnails[i].attr("src",imageDirectory+pic+".jpg");
}
});
});
When I perform my click function, an error returns saying "undefined is not a function".
I don't know why its doing this. Some help please.
When you iterate over the images collection, productThumbnails[i] returns the underlying HTMLImageElement which doesn't provide the attr() method. Try to wrap it with jQuery instead:
$(productThumbnails[i]).attr("src",imageDirectory+pic+".jpg");
Also, when using jQuery, the best way to access arbitrary data associated with your DOM elements is using the data() method:
var imageDirectory = $(this).data('directory');
var pictures = $(this).data('pictures');
As a bonus, you'll also get JSON deserialization out of the box and there's no need for JSON.parse():
var pictureArray = $(this).data('pictures');

Categories

Resources