How to pass Image from database in to javascript? - javascript

I am new to javascript and I'm trying to pass image from database into javascript, but I can not.
The problem code is :
'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';
and this is my code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="box">
<img id="image" />
</div>
<?php
$query = $this->db->get('product');
foreach($query->result() as $val):
?>
<script>
var images =
'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
</script>
<?php endforeach; ?>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Javascript random image</title>
<?php
/* Query the db */
$query = $this->db->get('product');
/* use php to generate the javascript array of images from db query */
echo "
<script type='text/javascript'>
var images=[];
var baseurl='".base_url()."';
var path='./images/burger/';";
foreach( $query->result() as $val ){
/* Add image to javascript array */
echo "images.push('{$val->image}');\n";
}
echo "
</script>";
?>
<script type='text/javascript'>
function rnd_index(a,b) {
return Math.round( a + ( Math.random() * ( b - a ) ) );
}
function randImg() {
var x = rnd_index( 0, images.length-1 );
document.getElementById('image').src = baseurl + path + images[ x ];
}
function orig__randImg() {
var size = images.length;/* This might be too large sometimes for the array */
var x = Math.floor( size * Math.random() );
document.getElementById('image').src = path + images[ x ];
}
/* Load a random image when the page has loaded */
window.onload=randImg;
</script>
</head>
<body>
<div id="box">
<img id="image" />
</div>
</body>
</html>

You need to create an array in javascript and push the image path.
Before <?php foreach(...
<script>
var images = [];
function randImg(images) {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
</script>
Inside the loop..
<script>
images.push("<?php echo base_url().'./images/burger/'.$val->image ?>");
</script>
After loop...
<script>
randImg(images);
</script>

Related

How to add the returned value from a JavaScript function into an HTML element [duplicate]

I am looking for a way to call a javascript number in the body of an html page. This does not have to be long and extravagant just simply work, I just want something like:
<html>
<head>
<script type="text/javscript">
var number = 123;
</script>
</head>
<body>
<h1>"the value for number is: " + number</h1>
</body>
</html>
Try This...
<html>
<head>
<script>
function myFunction() {
var number = "123";
document.getElementById("myText").innerHTML = number;
}
</script>
</head>
<body onload="myFunction()">
<h1>"The value for number is: " <span id="myText"></span></h1>
</body>
</html>
Use document.write().
<html>
<head>
<script type="text/javascript">
var number = 123;
</script>
</head>
<body>
<h1>
the value for number is:
<script type="text/javascript">
document.write(number)
</script>
</h1>
</body>
</html>
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write but
can't avoid <script> tag
<script type="text/javascript">
function get_param(param) {
var search = window.location.search.substring(1);
var compareKeyValuePair = function(pair) {
var key_value = pair.split('=');
var decodedKey = decodeURIComponent(key_value[0]);
var decodedValue = decodeURIComponent(key_value[1]);
if(decodedKey == param) return decodedValue;
return null;
};
var comparisonResult = null;
if(search.indexOf('&') > -1) {
var params = search.split('&');
for(var i = 0; i < params.length; i++) {
comparisonResult = compareKeyValuePair(params[i]);
if(comparisonResult !== null) {
break;
}
}
} else {
comparisonResult = compareKeyValuePair(search);
}
return comparisonResult;
}
var parcelNumber = get_param('parcelNumber'); //abc
var registryId = get_param('registryId'); //abc
var registrySectionId = get_param('registrySectionId'); //abc
var apartmentNumber = get_param('apartmentNumber'); //abc
</script>
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">
document.write(registrySectionId)
</script></td>
Here is another way it can be done .
function showData(m)
{
let x ="<div> added from js ";
let y = m.toString();
let z = "</div>";
let htmlData = x+y+z ;
content.insertAdjacentHTML("beforeend",htmlData);
}
You can do the same on document ready event like below
<script>
$(document).ready(function(){
var number = 112;
$("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>
or you can simply do it using document.write(number);.
<?php
$x1='<span id="x1"></span><script>document.getElementById("x1").innerHTML = x1;</script>';
$x2='<span id="x2"></span><script>document.getElementById("x2").innerHTML = x2;</script>';
$x3='<span id="x3"</span><script>document.getElementById("x3").innerHTML = x3;</script>';
?>
<html><body>
<script> var
x1="123",
x2="ABC",
x3=666;
</script>
<?php echo $x1 ?><br>
<?php echo $x2 ?><be>
<?php echo $x3 ?><be>
</body></html>
Index.html:
<html>
<body>
Javascript Version: <b id="version"></b>
<script src="app.js"></script>
</body>
</html>
app.js:
var ver="1.1";
document.getElementById("version").innerHTML = ver;
You cannot add JavaScript variable to HTML code.
For this you need to do in following way.
<html>
<head>
<script type="text/javscript">
var number = 123;
document.addEventListener('DOMContentLoaded', function() {
document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>

How can I implement this twbs-pagination

I am using this plugin to paginate my list items but I am confused about how to implement this to query to my table to pull and limit 10 or depending on my needs and display this inside in my <ul> tag.
Here is my sample.
Database.php
class Database{
protected $connection;
public function __construct(PDO $connection)
{
$this->connection = $connection;
}
public function getData(){
try{
$cmd = $this->connection->prepare("SELECT COUNT(*) FROM names");
$cmd->execute();
$rows = $cmd->fetchColumn();
$cmd=null;
return $rows;
}catch(PDOException $ex){
}
}
public function display($start,$perpage){
try{
$cmd = $this->connection->prepare("SELECT name FROM names LIMIT ? , ?");
$cmd->bindParam(1,$start);
$cmd->bindParam(2,$perpage);
$cmd->execute();
$rows = $cmd->fetchAll(PDO::FETCH_ASSOC);
$datali = '';
foreach($rows as $r){
$datali.='<li class="list-group-item">'.$r['name'].'</li>';
}
return $datali;
}catch(PDOException $ex){
}
}
}
index.php
require_once 'includes/config.php';
require_once 'includes/Database.php';
$pdo = new PDO(HOST,USER,PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$connectdb = new Database($pdo);
$rows = $connectdb->getData();
$page = $_GET['page'];
$per_page = 5;
$pages = ceil( $rows / $per_page );
if($page == 0)
$start = 0;
else
$start = ( $page - 1 ) * $per_page;
$data = $connectdb->display($start,$per_page);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
var pages = '<?php echo $pages;?>';
$('#mylist-ul').twbsPagination({
totalPages: pages,
visiblePages: 7,
href: '?page={{number}}'
});
});
</script>
</head>
<body>
<div class="wrapper">
<?php echo $data ?>
<ul class="list-group" id="mylist-ul"></ul>
</div>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.twbsPagination.min.js"></script>
</body>
</html>
It depends on what you want to display. If you want to display data from a database, here is an example:
Let's say you have table with 10 rows of data in it.
First we need to query the db and get all data from the table
$result = $con->query("SELECT * FROM table");
Now we need to count the rows we got.
$rows = $result->num_rows;
Let's say we want 5 items to be displayed in each page.
$per_page = 5;
We calculate the number of pages with
$pages = ceil( $rows / $per_page );
We will get 2 pages.
Now we will check the page we are on and set the starting point
$page = isset( $_GET['page'] ) ? $con->real_escape_string($_GET['page']) : 0;
$page == 0 ? $start = 0 : $start = ( $page - 1 ) * $per_page;
$curpag = ( $start == 0 ) ? 1 : ( $start / $per_page ) + 1 ;
Now it's time to display data from the table
$result = $con->query("SELECT * FROM table ORDER BY id ASC LIMIT $start, $per_page");
while($row = $result->fetch_array(MYSQLI_ASSOC)):
//display data in table/list/etc.
endwhile;
We add the pagination element with
<ul id="pagination" class="pagination-sm"></ul>
And finally we initialise the plugin
<script>
var pages = '<?php echo $pages;?>'; //We store the number of pages in a variable to use it below
$('#pagination').twbsPagination({
totalPages: pages,
visiblePages: 7,
href: '?page={{number}}' //Very important!
});
</script>

refreshing div tag without refreshing a

I want to reload the div tag in click event.I want to generate random password in click event.now whole page get refreshed.This should take some time.so I want to refresh div tag every 3 second or in click event.Here I attached my code.
<body>
hello
<div class="refresh">
<?php
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
echo $pwd=randomPassword();
?>
</div>
<button class="click">click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".click").click(function(){
location.reload();
});
});
</script>
</body>
On click of a button, you are reloading the page using location.reload(); For only refreshing a div you need to modify your code.
<body>
hello
<div class="refresh">
</div>
<button class="click">click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".click").click(function(){
var str = randomPassword();
$(".refresh").html(str);
});
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
});
</script>
</body>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
setInterval(RandPwd,30000);
function RandPwd()
{
var pwd = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
pwd += possible.charAt(Math.floor(Math.random() * possible.length));
$(".refresh").html(pwd);
return false;
}
</script>
</head>
<body>
hello
<div class="refresh">
</div>
<button class="click" onclick="return RandPwd();">click me</button>
</body>
</html>
This is for refreshing the div tag without reloading the page.
<script>
var auto_refresh = setInterval(function () {
$('.refresh').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 3000);
</script>

Same random image on push with a button

I am trying to make this code to generate a random number of 10 images, so every time I click the button I will get a random number of images and I just want this 1 image and the button doesn't disappear so I can try again.
<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
function randomImg1() {
myImages1 = "Myimage.jpg";
var rnd = Math.floor( Math.random() * 10 );
document.write(myImages1[rnd]);
}
</script>
</body>
</html>
myImages1 is a string an not an array. And you need to multiple the random() by the number of elements in the array.
function randomImg1() {
var myImages1 = ['Myimage.jpg'];
var rnd = Math.floor(Math.random() * myImages1.length );
document.write(myImages1[rnd]);
}
You'll need to update the content dynamically, not using document.write. In addition, myImages1 must be an array.
<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
function randomImg1() {
myImages1 = new Array();
myImages1[0] = "Myimage.jpg";
myImages1[1] = "Myimage1.jpg";
var rnd = Math.floor( Math.random() * myImages1.length ); //incorporated other solution
document.getElementById("image").innerHTML = "<img src='" + myImages1[rnd] + "' alt='image'></img>";
}
</script>
<div id="image"></div>
</body>
</html>

multiple records using the same script

I have built a voucher website, where each voucher has a countdown timer. When you view a voucher the countdown works fine, however...
I also have a summary page with multiple vouchers (using a repeat region on the recordset)... when I apply the script to each of the vouchers the script doesn't work.
The HMTL:
<h3 class="remaining"><?php echo $row_rs_dealItem['dateend']; ?> remaining</h3>
The JAVASCRIPT external file:
$(document).ready(function(){
$('.remaining').each(function(){
var expiry_date = Date.createFromMysql($(this).html());
var current_date = new Date();
console.log(expiry_date.getTime() );
console.log(current_date.getTime());
if (expiry_date.getTime() > current_date.getTime()) {
var time_diff = Math.floor((expiry_date.getTime() - current_date.getTime()) / (1000*60*60));
console.log(expiry_date.getTime() - current_date.getTime());
console.log(time_diff);
days_diff = Math.floor(time_diff / 24);
hours_diff = time_diff % 24;
$(this).html(days_diff + ' days ' + hours_diff + ' hours');
}
else{
$(this).html('expired');
}
});
});
Date.createFromMysql = function(mysql_string)
{
if(typeof mysql_string === 'string')
{
var t = mysql_string.split(/[- :]/);
//when t[3], t[4] and t[5] are missing they defaults to zero
return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
}
return null;
}
The JAVASCRIPT inline:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scripts/script.js"></script>
<script type="text/javascript">
var reference = '<?php echo $row_rs_dealItem['reference']; ?>';
var today = Date.createFromMysql('<?php echo date('Y-m-d h:i:s'); ?>');
var contractstarts = <?php echo ($row_rs_dealItem['datestart'] == '0000-00-00') ? '""' : 'Date.createFromMysql("' . $row_rs_dealItem['datestart'] . '")'; ?>;
var contractexpires = <?php echo ($row_rs_dealItem['dateend'] == '0000-00-00') ? '""' : 'Date.createFromMysql("' . $row_rs_dealItem['dateend'] . '")'; ?>;
</script>
I hope this is enough data for you.
thanks
I realised that I had effectively copied the code from one page to another and the record sets had different names :(

Categories