how to pass php array on change of select in jQuery? - javascript

Let me tell you in brief what I am doing ..
I am doing pagination using a library where the pagination is just showing the 3 <li> at a time.
and What I am doing on that <li> is I have a php array with me and I am creating a table in that <li> that each <li> will have table with 8 rows so the 8 elements of the array has been displayed with the help of php code.
This is the code.
<?php
$data = array();
$no_of_Items = 8;
$k = 1;
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "striker" . $i;
}
?>
<select id="view" >
<option value="1">Midfielder</option>
<option value="2">Striker</option>
<option value="3">Defender</option>
<option value="4">Goal-Keeper</option>
</select>
<div id="pagination">
<ul id="demo">
<?php
$lis = ceil(count($data) / $no_of_Items);
for ($i = 1; $i <= $lis; $i++) {
?>
<li>
<table id="tbl-li">
<?php
for ($j = 1; $j <= $no_of_Items; $j++) {
if (empty($data[$k - 1])) {
break;
}
?>
<tr style="padding: 0; margin: 0;">
<td><?php echo $data[$k - 1]; ?></td>
<td>CHE</td>
<td>11.5</td>
<td>142</td>
</tr ><?php $k++; } ?>
</table>
</li>
<?php } ?>
</ul>
</div>
so what I am doing now is just passing the one array to the pagination div but i have 4 arrays for defender as well as for all the item contains in the select tag .
So my final question is how to provide to my code the php when I select the appropriate option from the select?
I have tried this but I know this will not going to work so any suggestion or any other way?
My js
var selectval;
$('#view').on('change', function () {
selectval = $(this).val();
});
if (selectval === 1)
{
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "midfielder" . $i;
}
?>
}
else if (selectval === 2) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "striker" . $i;
}
?>
}
else if (selectval === 3) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "defender" . $i;
}
?>
}
else if (selectval === 3) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "goalkeeper" . $i;
}
?>
}

Try This it will work..
$('#view').select(function(){
var valselect = $('#view').val();
console.log(valselect);
var data = [];
var i, j, k = 1;
var code = '';
var no_item = 8;
if (valselect === "1")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Midfielder" + i;
}
console.log(data);
}
else if (valselect === "2")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Striker" + i;
}
console.log(data);
}
else if (valselect === "3")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Defender" + i;
}
console.log(data);
}
else if (valselect === "4") {
for (i = 1; i <= 50; i++) {
data[i - 1] = "Goal-keeper" + i;
}
console.log(data);
}
var lis = Math.ceil(data.length / no_item);
console.log(lis);
for (i = 1; i <= lis; i++)
{
console.log("outerloop="+i);
code += "<li><table id='tbl-li'>";
for (j = 1; j <= no_item; j++) {
console.log("j=" + j);
if (data[k - 1])
{
// console.log("k=" + k);
code += "<tr><td><img src='/img/info.png'>" + data[k - 1] + "</td><td>CHE</td><td>11.5</td><td>142</td></tr>";
k++;
}
else {
// console.log("val k=="+k);
break;
}
}
code += "</table></li>";
}
// console.log(code);
// $('#demo').append();
$('#demo').html(code);
});

Related

How to select values from more tasks assigned to same project

I have an app where I can create a Project and, inside the Project, I can create Tasks. For every Task, I can add a percent and calculate a price (example picture 1).
Then I have a report page where I want to calculate all the prices from all of the Tasks of same project (example picture 2). Now I used a code with logic that works for other sums on same project (example picture 3), but when I use this code for the percent sum of all tasks its not working properly (example picture 4, in this picture I put to display the array not the sum)
picture 1:
picture 2 (but here the problem is that just the first array is corrent the other are not):
picture 3 (same code - works good):
Code:
if($projectTaskIds && count($projectTaskIds)){
$realTime = 0;
$estimateCost = 0;
$itemName = '';
$realCost = 0;
$realCostArr = array();
$totalCalEArr = array();
foreach ($projectTaskIds as $key => $projectTaskId) {
// echo $projectTaskId['id'];
// echo "<br>";
$calB = 0;
$calC = 0;
$itemtotal = 0;
$items = get_items_by_type('task', $projectTaskId['id']);
if($items && count($items) > 0){
$itemNo = 1;
foreach ($items as $key => $item) {
$itemtotal += ($item["rate"]*$item["qty"]);
$itemName .= '<div>'.$itemNo.'.'.$item["description"].' <b>('.round($item["qty"]).')</b>'.'</div>';
$itemNo++;
}
}
// =============== the code that doesn't work ============
$calF = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
$calG = get_task_custom_billable_amount($aRow['id']);
if($aRow['task_item_percentage']){
$calE = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
}
else {
$calE = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$totalCalE = $calE;
$totalCalEArr[] = $totalCalE;
if($totalCalEArr && count($totalCalEArr) > 0){
$totalsCalEaMount = 0;
foreach ($totalCalEArr as $key => $totalvalue) {
$totalsCalEaMount += $totalvalue;
}
}
// =============== the code that doesnt work ============
$realTime += get_calc_task_real_logged_time($projectTaskId['id']);
$calB = get_task_custom_billable_amount($projectTaskId['id']);
if($aRow['task_item_percentage']){
$calC = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
} else {
$calC = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$estimateCost += round($itemtotal+($calA * $aRow['task_duration'] / 60));
$realCost = round($itemtotal+$calB);
// if($calC = 0){ $realCost = round($itemtotal+$calB);} else { $realCost = round($itemtotal+$calB+$calC);
// }
$realCostArr[] = $realCost;
}
if($realCostArr && count($realCostArr) > 0){
$realCostAmount = 0;
foreach ($realCostArr as $key => $reslcostvalue) {
$realCostAmount += $reslcostvalue;
}
}
}
$outputName = '';
$relName = '';
$row[] = $loop;
if ($aRow['rel_name']) {
$relName = task_rel_name($aRow['rel_name'], $aRow['rel_id'], $aRow['rel_type']);
$link = task_rel_link($aRow['rel_id'], $aRow['rel_type']);
$relName = '<span class="hide"> - </span><a class="text-muted task-table-related" data-toggle="tooltip" title="' . _l('task_related_to') . '" href="' . $link . '">' . $relName . '</a>';
}
$row[] = $relName;
$row[] = count($projectTaskIds);
$row[] = $itemName;
$row[] = $aRow['task_duration']*count($projectTaskIds);
$row[] = round($realTime/60);
$row[] = round($estimateCost);
$row[] = round($realCostAmount);
$row[] = '';
$row[] = $totalCalEArr; // display as array or $row[] = $totalsCalEaMount; to display as a sum
$output['aaData'][] = $row;
$loop++;
}

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();
};

Display a random string in a html form

I want to create a form where one of the values already has a random string filled in. I've tried PHP and javascript however it keeps displaying the variable name instead of the variable... Any help would be much as appreciated!
<form name="name" method="post" action="sendform.php">
<table width="450px">
<tr>
<td valign="top">
<label for="number">Number</label>
</td>
<td valign="top">
<input type="text" value="Insert random string here" maxlength="50" size="30">
</td>
</tr>
</table>
</form>
script:
<script>
function generateRandomString($length = 10) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
</script>
php
function generateRandomString($length = 10) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
The simple, secure, and correct answer is to use RandomLib and don't reinvent the wheel.
With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
<form name="name" method="post" action="sendform.php">
<table width="450px">
<tr>
<td valign="top">
<label for="number">Number</label>
</td>
<td valign="top">
<input type="text" value="<?php echo random_str(10); ?>" maxlength="50" size="30">
</td>
</tr>
</table>
</form>
Do this
<?php $length = 10;
$randomString = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
?>
<td valign="top">
<input type="text" value="<?php echo $randomString;?>" maxlength="50" size="30">
</td>
Output will be mix of number and alphabet like this: 10whDMtuLO
Also, set the length of the string in $length as per your need.
Try this..
<?php $rand = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 7); ?>
.
.
.
<td valign="top">
<input type="text" value="<?php echo $rand; ?>" maxlength="50" size="30">
</td>
You can Refer this answer by Roko C. Buljan
function randNumber(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
}
document.getElementById("foo").value = randNumber(10,'A');
<textarea id='foo' style='width:100%;height:200px'></textarea>
function for making sh1 hash
function sha1 ( str ) {
var rotate_left = function(n,s) {
var t4 = ( n<<s ) | (n>>>(32-s));
return t4;
};
var lsb_hex = function(val) {
var str="";
var i;
var vh;
var vl;
for( i=0; i<=6; i+=2 ) {
vh = (val>>>(i*4+4))&0x0f;
vl = (val>>>(i*4))&0x0f;
str += vh.toString(16) + vl.toString(16);
}
return str;
};
var cvt_hex = function(val) {
var str="";
var i;
var v;
for( i=7; i>=0; i-- ) {
v = (val>>>(i*4))&0x0f;
str += v.toString(16);
}
return str;
};
var blockstart;
var i, j;
var W = new Array(80);
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
var A, B, C, D, E;
var temp;
str = this.utf8_encode(str);
var str_len = str.length;
var word_array = new Array();
for( i=0; i<str_len-3; i+=4 ) {
j = str.charCodeAt(i)<<24 | str.charCodeAt(i+1)<<16 |
str.charCodeAt(i+2)<<8 | str.charCodeAt(i+3);
word_array.push( j );
}
switch( str_len % 4 ) {
case 0:
i = 0x080000000;
break;
case 1:
i = str.charCodeAt(str_len-1)<<24 | 0x0800000;
break;
case 2:
i = str.charCodeAt(str_len-2)<<24 | str.charCodeAt(str_len-1)<<16 | 0x08000;
break;
case 3:
i = str.charCodeAt(str_len-3)<<24 | str.charCodeAt(str_len-2)<<16 | str.charCodeAt(str_len-1)<<8 | 0x80;
break;
}
word_array.push( i );
while( (word_array.length % 16) != 14 ) word_array.push( 0 );
word_array.push( str_len>>>29 );
word_array.push( (str_len<<3)&0x0ffffffff );
for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for( i= 0; i<=19; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=20; i<=39; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=40; i<=59; i++ ) {
temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
for( i=60; i<=79; i++ ) {
temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B,30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
}

Carousel need to start from middle slide on page load

I have using Multi Carousel to display complete months dates in a slider. Each date some data be hide on click. When I browse to Multi Carousel clicked date is today,s date, Means active class for slides is current date.
But as slider have 30 days. so slider always start from day 1. I always need to slide it to current date by clicking next arrow.
Like today is sep-26. If you check following page you find a date slider there which is on sep-1 now. so to get sep-26 you need to slide next. http://prosport.guru/ps/game.php
I want that when page load slider should moves to current date auto. I have add auto class to current date slide but it did not work.
Following is my code for Multi Carousel.
<?php
$page2 = $_SERVER["PHP_SELF"];
$page2 = explode("/", $page2);
$page2 = $page2[count($page2) - 1];
$id_sport2 = $_GET["id_sport"];
$m = date("m");
$day = date("d");
$year = date("Y");
$dates = array();
$dates2 = array();
$tmp = array();
for ($i = 1; $i < 32; $i++) {
if ($i < 10) {
$ii = "0$i";
} else {
$ii = $i;
}
$date = "$year-$m-$ii";
//$date = date("Y-m-d", strtotime($date));
if ($i % 3 != 0) {
array_push($tmp, $date);
if ($i == 60) {
if (count($tmp != 0)) {
array_push($dates2, $tmp);
}
}
} else {
array_push($tmp, $date);
array_push($dates2, $tmp);
$tmp = array();
}
array_push($dates, $date);
}
///print_r($dates2);
?>
<div class="row" style="border:1px solid silver; background: #a0a0a0; color: white; ">
<div class="MultiCarousel" data-items="1,3,5,6" data-slide="3" id="MultiCarousel2" data-interval="1000" >
<div class="MultiCarousel-inner">
<?php
$cpt = 0;
for ($i = 0; $i < count($dates2); $i++) {
$line = $dates2[$i];
$today = date("Y-m-d");
if (empty($_GET["date"])) {
$goto = $today;
if (in_array($today, $line)) {
$active = "active";
} else {
$active = "";
}
} else {
$dt = $_GET["date"];
$goto = $dt;
if (in_array($dt, $line)) {
$active = "active";
} else {
$active = "";
}
}
for ($x = 0; $x < count($line); $x++) {
$el = $line[$x];
if (!empty($_GET["date"])) {
$dt = $_GET["date"];
if ($el == $dt) {
$color = "red";
} else {
$color = "white";
}
} else {
if ($el == $today) {
$color = "red";
} else {
$color = "white";
}
}
$href = "$page2?id_sport=$id_sport2&date=$el";
if ($x == 0) {
//echo "<div class='col-lg-1 col-xs-1'> </div>";
//echo "<div class='col-lg-10 col-xs-10'>";
}
/* echo ' <div class="col-md-4 col-xs-4 col-lg-4 ">
'.$el.'</div>';
*/
if ($x == 2) {
//echo "</div>";
}
?>
<div class="item " style="text-align:center">
<a href="<?php echo $href; ?>" >
<p class=" sportName mydate p-date" real="<?php echo $el; ?>" style="color:white; font-size: 12px; text-align: center;" >
<?php
$date = $el;
$month_name = ucfirst(strftime("%b", strtotime($date)));
$day_number = ucfirst(strftime("%d", strtotime($date)));
echo $month_name . ' ' . $day_number;
?>
</p>
</a>
</div>
<?php
}
}
echo "<input type='hidden' value='$goto' id='cd'>";
?>
</div>
<button class="btn btn-primary btn-sm leftLst" style="border-radius: 0px; top: calc(64% - 20px);"><</button>
<button class="btn btn-primary btn-sm rightLst fw" style="border-radius: 0px; top: calc(64% - 20px);">></button>
</div></div>
<script>
$(document).ready(function () {
var cd = $("#cd").val();
$(".mydate").each(function () {
var cd_tmp = $(this).attr("real");
if (cd_tmp != cd) {
//alert(cd_tmp+" is different from "+cd);
//$(".fw").click();
} else {
$(this).addClass("tag tag-danger active");
//break;
}
})
})
</script>
This jquery script will move it to the current date on page load.
$(function() {
// Get month and day, ex. "Sep 21"
var monthAndDay = new Date().toLocaleString("en-us", { month: "short" }) + ' ' + new Date().getDate();
// Locate the carousel item using month and day string
var $list = $('#MultiCarousel2 > div .item');
var $carouselToday = $('#MultiCarousel2 > div .item a p:contains('+monthAndDay+')');
var $parent = $carouselToday.closest('.item');
var index = $list.index( $parent );
var itemWidth = $list.eq(0).width();
var position = (index * itemWidth) * -1;
$('#MultiCarousel2 > div').css({"transition": "0s", "transform": "translate("+ position +"px)"});
$('#MultiCarousel2 > div').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function() {
$(this).css({"transition": "1s ease all"})
});
});

PHP and Javascript getelementbyid, how to pass on parameters

I have a Javascript function that is called many time within a while loop with <div id='c$value'>.
When calling countdown() I would need to pass on some parameters. In this case $m and $s.
How can this be done ?
window.onload = function() {
<?php
$nbcounters = 5;
for ($i = 0; $i < $nbcounters; $i++) {
echo "countdown('c$i', 0, 7);";
}
?>
}
the php code
<?php
$value = 0;
while ($value < $nbcounters) {
$m = rand(1, 3);
$s = rand(10, 20);
echo "<div id='c$value'></div><br>";
$value++;
}
?>
Thanks!

Categories

Resources