Ordered list with random numbers between 1 and 49 - javascript

I have some problems to Code an simple PHP ordered list that print out a random number list between 1 and 49.
The Main Code
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>AJAX</title>
<meta name="viewport" content=
"width=device-width; initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="lib/css/stil.css" />
<script type="text/javascript"
src="lib/js/script.js"></script>
</head>
<body>
<h1>Ziehung der Lottozahlen</h1>
<button id="frage">Starte die Ziehung</button>
<div id="antwort">
</div>
</body>
</html>
Here the external PHP Code to randomize the numbers
<?php
$zahlen = range (1, 49);
shuffle($zahlen);
for ($i = 0; $i < 6; $i++) {
echo $zahlen[$i] . " ";
}
?>
And here the Java script
var resOb = new XMLHttpRequest();
window.onload = function() {
document.getElementById("frage").onclick =
function () {
resOb.open('get', 'lottozahlen1.php', true);
resOb.onreadystatechange = function () {
if (resOb.readyState == 4) {
document.getElementById("antwort").innerHTML =
resOb.responseText;
}
};
resOb.send(null);
};
};
T
Now my question...how i can let Show the numbers in a ordered list?

use PHP code below way
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);

You could split the string, map the values as number and sort the array. Then generate the wanted list items and put it to the wanted unordered list.
var lotto = '22 34 14 10 99',
list = lotto
.split(' ')
// .map(Number)
// .sort(function (a, b) {
// return a - b;
// })
.reduce(function (list, a) {
var li = document.createElement('li');
li.innerHTML = a;
list.appendChild(li);
return list;
}, document.createElement('ol'));
document.body.appendChild(list);

Extending Kool-Mind's answer:
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
Try adding the code below(to generate the list):
<script>
$('#button').click(function(){
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
})
</script>
Hope it helps =)
EDIT
This should be working fine now, hope it helps =)
<button id="button">Button</button>
<div id="newDiv"></div>
<script>
var clicked = false;
$('#button').click(function(){
if (!clicked){
<?php
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] = rand(1,49);
}
sort($arr,1);
?>
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
clicked = true;
}
})
</script>

Related

How to asynchronously preload images

I have a set of videos that I exported to frames and show current frame based on scroll position (something like this but using image frames instead of video)
And using this in <head> casues lots of initial delay but afterwards the frame transition is very smooth.
<?php for ($i = 0; $i <= 99; $i++) {
$number = $i < 10 ? '0'.$i : $i; ?>
<link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-1-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
<?php for ($i = 0; $i <= 99; $i++) {
$number = $i < 10 ? '0'.$i : $i; ?>
<link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-2-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
<?php for ($i = 0; $i <= 99; $i++) {
$number = $i < 10 ? '0'.$i : $i; ?>
<link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-3-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
...
Any thought on how can I only preload the first scene and the rest to be preloaded after window.onload ?
I ended up Doing it like so:
function preloadRestOfScenes() {
/* Scene 2 */
let html = "";
for (let i = 0; i <= 249; i++) {
let number;
if (i < 10) {
number = "00" + i;
} else if (i >= 10 && i < 100) {
number = "0" + i;
} else {
number = i;
}
html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/02/optim/scene-2-${number}.jpg" as="image">`;
}
document.querySelector("head").insertAdjacentHTML("beforeend", html);
/* Scene 3 */
html = "";
for (let i = 0; i <= 549; i++) {
let number;
if (i < 10) {
number = "00" + i;
} else if (i >= 10 && i < 100) {
number = "0" + i;
} else {
number = i;
}
html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/03/optim/scene-3-${number}.jpg" as="image">`;
}
document.querySelector("head").insertAdjacentHTML("beforeend", html);
/* Scene 4 */
html = "";
for (let i = 0; i <= 299; i++) {
let number;
if (i < 10) {
number = "00" + i;
} else if (i >= 10 && i < 100) {
number = "0" + i;
} else {
number = i;
}
html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/04/optim/scene-4-${number}.jpg" as="image">`;
}
document.querySelector("head").insertAdjacentHTML("beforeend", html);
}
And
window.onload = () => {
preloadRestOfScenes();
};

google spreadsheet search from textfinder and return to HTML

Id like search by textFinder and return it to an array for html table. I have multiple spreadsheets and my intention is to retrieve spreadsheets data from one text input using textFinder then send them to a HTML page(using google HTML templates).
I have tried with the below codes but couldn't find a solution please help.
Code.gs
function doGet(){
var html = HtmlService.createTemplateFromFile("index");
var output = html.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
return output;
}
function getFilter(search){
var ssID = "Sheet ID",
sheet = SpreadsheetApp.openById(ssID).getSheets()[2];
var Avals = sheet.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
var ranges = [];
if ("name" in search && search.name != "") {
ranges = sheet.getRange(2, 4, Alast - 1, 3).createTextFinder(search.name).findAll();
}
if ("ac" in search && search.ac != "") {
var acRanges = sheet.getRange(2, 3, Alast - 1, 1).createTextFinder(search.ac).findAll();
if (ranges.length > 0) {
ranges = ranges.filter(function(r1) {return acRanges.some(function(r2) {return r1.getRow() == r2.getRow()})});
} else {
ranges = acRanges;
}
for (i = 0; i < ranges.length; i++) {
var row = ranges[i].getRow();
var lastCol = sheet.getLastColumn();
var values = sheet.getRange(row, 1, 1, lastCol).getDisplayValues(); //get all values for the row
return values;
}
}
}
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script type="text/javascript">
function setPageValues () {
var search = document.getElementsByName('searchtext')[0].value;
var ac = document.getElementsByName('ac')[0].value;
var obj = {};
if (!search && !ac) alert("No search values.");
if (search) {
obj.name = search;
}
if (ac) {
obj.ac= ac;
}
google.script.run.withSuccessHandler(disp).getFilter(obj);
}
</script>
</head>
<body>
<input type="text" name="ac">
<input type="text" name="searchtext">
<input type="button" value="Search" onclick="setPageValues();">
<br /><br />
<div name="resultbox">
<? var values = getFilter(); ?>
<table>
<? for (var i = 0; i < values.length; i++) { ?>
<tr>
<? for (var j = 0; j < values.length; j++) { ?>
<td><?= values[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</div>
</body>
<script>
</script>
</html>

Why i'm getting error: "SyntaxError: Unexpected token <"?

This is the code i'm using:
<?php
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($"http://newsxpressmedia.com/files/radar-simulation-files")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
$files[] = $file;
$curimage++;
}
}
closedir($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
#Timer_Countdown{
background:black;
color:yellow;
font-weight:bold;
text-align:center;
}
</style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
var images = <?=json_encode($files)?>;
//var images = [];
var x = -1;
var swap_hours = 0;
var swap_minutes = 0;
var swap_seconds = 5;
var down_counter_hours;
var down_counter_minutes;
var down_counter_seconds;
function initTimer() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
counter = setInterval(switcher, 1000);
}
function restartCounter() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
}
function switcher() {
down_counter_seconds--;
if (down_counter_hours <= 0 && down_counter_minutes <= 0 && down_counter_seconds <= 0) {
swapColor();
restartCounter();
}
if (down_counter_seconds <= 0 && down_counter_minutes > 0) {
down_counter_seconds = 60;
down_counter_minutes--;
}
if (down_counter_minutes <= 0 && down_counter_hours > 0) {
down_counter_minutes = 60;
down_counter_hours--;
}
document.getElementById("Timer_Countdown").innerText = down_counter_hours+":"+down_counter_minutes+":"+down_counter_seconds;
}
function swapColor() {
displayNextImage();
}
</script>
<div id="div_hours" class="div_box"></div>
<div id="div_minutes" class="div_box"></div>
<div id="div_seconds" class="div_box"></div>
<div id="div_switcher" class="div_box"></div>
</head>
<body onload = "initTimer()">
<div id="Timer_Countdown"> </div>
<img id="img" src="http://newsxpressmedia.com/files/theme/radar000005.Gif">
<button onclick="displayPreviousImage(); restartCounter()">Previous</button>
<button onclick="displayNextImage(); restartCounter()">Next</button>
</body>
</html>
The error is on the line:
var images = <?=json_encode($files)?>;
If i change this line to this line:
var images = [];
Then the code is working fine but without using the php files variable.
Something is wrong with the line: var images = <?=json_encode($files)?>;
I tried to change this line to: echo json_encode($images); or to var images = echo json_encode($files); but same error.
I'm using weebly to build my site and my site server is on ipage.com
How can i fix the error ?
It looks like you don't have short tags enabled(and are using a pre 5.4 php version), thus the line <?=json_encode($files)?> is not parsed by php and is just send straight through. var images = <... is not a valid javascript expression. Here's some information about php's short_open_tag parameter: http://php.net/manual/en/ini.core.php#ini.short-open-tag
A couple of changes. Change
$pattern ="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)";
to
$pattern = '/\.(png|jpg|jpeg|gif)$/i';
and
eregi($pattern, $file)
to
preg_match($pattern, $file)
and see what happens. eregi deprecated as PHP 5.3.0.
You are using '=' inside the PHP tags. Try this:
var images = <?json_encode($files)?>;

javascript conflict between ajax pagination and flowplayer plug-in

I applied an ajax pagination in my web project it worked well however my flowplayer plug-in stopped working i think they are in conflict or they are overwriting each other's javascript so i ve searched for a while in web but i couldn t find the solution. ( i tried even noConflict method)
What should i do ? Can anyone help me please ?
Here is my index.php:
<?php
// This first query is just to get the total count of rows
$sql = "SELECT id_video FROM video ORDER BY id_video DESC";
$res = $connexion->query($sql);
$count=$res->rowCount();
//print_r($count);
// Here we have the total row count
//$total_rows = $row[0];
// Specify how many results per page
$rpp = 4;
// This tells us the page number of our last page
$last = ceil($count/$rpp);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Exemple</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/typocolor.css" />
<link rel="stylesheet" href="css/index_media_ie.css" />
<link rel="shortcut icon" href="image/favicon.ico" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600&subset=latin,latin-ext,cyrillic-ext' rel='stylesheet' type='text/css'>
<script>
$(document).ready(function()
{
flowplayer(".player", "./flowplayer/flowplayer-3.2.16.swf",{
clip: {
autoPlay: false,
autoBuffering: false
}
});
});
</script>
<script type="text/javascript" >
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
function request_page(pn){
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
var hr = new XMLHttpRequest();
hr.open("POST", "pagination_parser.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "<li>";
html_output += "<article>";
html_output += "<h3>"+itemArray[0]+"</h3>";
html_output += "<a class=\"player\" href="+itemArray[1]+" style=\"border:1px solid #bfbfbf;display:block;width:90%;height:250px;position:relative;margin:auto;padding:5px;background-color:white;box-shadow: 0px 0px 5px rgb(204, 204, 204);\"></a>";
html_output += "<p>"+itemArray[2]+"</p>";
html_output += "</article>";
html_output += "</li>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
// Change the pagination controls
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
</head>
<body>
<div id="wrapper">
.
.
.
</div>
<script src="./js/jquery.js"></script>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
<!-- bxSlider Javascript file -->
<script src="./js/bxslider/jquery.bxslider.min.js"></script>
<!-- bxSlider CSS file -->
<link href="./js/bxslider/jquery.bxslider.css" rel="stylesheet" />
<script src="./flowplayer/flowplayer-3.2.12.min.js"></script>
<script src="./js/comportement.js"></script>
<script> request_page(1); </script>
</body>
</html>
and pagination_parser.php (which i found it on developphp.com)
<?php
// Make the script run only if there is a page number posted to this script
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9]#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9]#', '', $_POST['last']);
$pn = preg_replace('#[^0-9]#', '', $_POST['pn']);
// This makes sure the page number isn't below 1, or more than our $last page
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last) {
$pn = $last;
}
// Connect to our database here
include_once("bdd.php");
$connexion->exec("SET CHARACTER SET utf8");
// This sets the range of rows to query for the chosen $pn
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "SELECT * FROM video ORDER BY id_video DESC $limit";
$res = $connexion->query($sql);
//$query = mysqli_query($db_conx, $sql);
$dataString = '';
while($row = $res->fetch(PDO::FETCH_ASSOC))//mysqli_fetch_array($query, MYSQLI_ASSOC)){
{
$titre=$row['titre'];
$description=$row['description'];
$src=$row['source_video'];
//$itemdate = strftime("%b %d, %Y", strtotime($row["datemade"]));
$dataString .= $titre.'|'.$src.'|'.$description.'||';
}
// Close your database connection
//mysqli_close($db_conx);
// Echo the results back to Ajax
echo $dataString;
exit();
}
?>
Try to comment out and execute your script I think its jQuery conflicting with it.

PHP post variable is not being rendered

I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>

Categories

Resources