Animation on CSV array changes - php

I have a simple page that displays race results. The results are pulled from a CSV file which updates upon completion of each race. The changes could be subtle so would like to have an animation, fade in/out or colour change etc, only if results are different. I want to add a to the table ONLY if the CSV file has new results as a visual aid to the update.
EDIT: I am unsure where to start on implementation so no code is reflected below. The CSV is scanned every 1 second and table updated. The outcome I want is for the table results to have an animation if/when array results change, else no animation.
EDIT 2: I have attempted to output the current racer number from the results data ($csv[1]) to a file and then check that against the current race number but it doesn't seem to work. When I pull $lastrace[0] and $csv[1] they are always the same number. I thought having it higher in the PHP would get $lastrace before writing the new number but doesn't appear so.
// Get Racer No from previous race
$lastrace = str_getcsv(file_get_contents('lastraceno.txt'));
// Puts current racer no to CSV file
$file = fopen("lastraceno.txt","w");
fputcsv($file,explode(',',$csv[1]));
fclose($file);
My code as it stands is as below - have trimmed some irrelevant code.
index.php
<head>
<script src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('table.php', function(){
setTimeout(refreshTable, 1000);
});
}
</script>
</head>
<body background="timebg.jpg">
<div id="tableHolder"></div>
</body>
table.php
<?php
$f_pointer=fopen("csv.txt","r"); // file pointer
while(! feof($f_pointer)){
$csv=fgetcsv($f_pointer);
foreach($csv as &$val){
if($val === "" || $val === false || $val === null) $val = "NA";
}
}
?>
<table>
<tr>
<td><?php echo $csv[2] ?> <?php echo $csv[3]?></td>
</tr>
</table>

Solved
The racer number is $csv1 in my Array from the results file. I found writing the $csv1 to a new CSV file and comparing $csv1 to $lastrace[0] each refresh to work.
Using an if else statement I compared the info and set a variable depending if there was a match or not.If the data matched the variable is '0' and no action is required. If $csv1 did not match $lastrace[0] the variable is '1' and the new race number sent to the lastraceno.txt for future updates.
I could then set a CSS class based on if the variable was 0 or 1.
CSS animation achieved with [https://daneden.github.io/animate.css/]Animate.CSS1
index.php
<head>
<script src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('table.php', function(){
setTimeout(refreshTable, 1000);
});
}
</script>
</head>
<body background="timebg.jpg">
<div id="tableHolder"></div>
</body>
table.php
<?php
$f_pointer=fopen("csv.txt","r"); // file pointer
while(! feof($f_pointer)){
$csv=fgetcsv($f_pointer);
}
// Replace blank lines with NA
foreach($csv as &$val){
if($val === "" || $val === false || $val === null) $val = "NA";
}
// Get Racer No from previous race
$lastrace = str_getcsv(file_get_contents('lastraceno.txt'));
// Puts current racer no to CSV file
if ($lastrace[0]==="$csv[1]") {
$newrace = 0; // This is not a new race
} else {
$newrace = 1; // This is a new race
$file = fopen("lastraceno.txt","w");
fputcsv($file,explode(',',$csv[1]));
fclose($file);
}
if ($newrace == '1') {
$newtimes = "class='animated zoomIn'";
} else { }
<table <?php echo $newtimes ?>>
<tr>
<td>Text to animate</td>
</tr>
</table.

Related

Asynchronus-PHP Upload Huge csv data into MYSQL

I tried to upload around 20k rows CSV into SQL using async method referring to this post :
How to import a huge CSV file with 200,00 rows to MySQL (asynchronous and fast)?
The script already running and success when I upload 10000 data, but when I checked into the database, I found that only half rows (5000 rows) were Inserted.
I've tried to change the $batchsize from 1000 to 100, only 9400rows inserted instead of supposedly 10000 rows
here's my current code :
index.php :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>csv upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" />
</form>
</body>
</html>
upload.php :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script>
//Declaration of function that will insert data into database
function senddata(filename){
var file = filename;
$.ajax({
type: "POST",
url: "senddata.php",
data: {file},
async: true,
success: function(html){
$("#result").html(html);
}
})
}
</script>
<?php
$batchsize = 100; //split huge CSV file by 1,000, you can modify this based on your needs
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = explode(".", $name);
$ext = $ext[1];
$tmpName = $_FILES['csv']['tmp_name'];
if($ext === 'csv'){ //check if uploaded file is of CSV format
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle)) !== FALSE) {
//splitting of CSV file :
if ($row % $batchsize == 0):
$file = fopen("minpoints$row.csv","w");
endif;
$csv[$row]['col1'] = $data[0];
$csv[$row]['col2'] = $data[1];
$min = $data[0];
$points = $data[1];
$json = "'$min', '$points'";
fwrite($file,$json.PHP_EOL);
//sending the splitted CSV files, batch by batch...
if ($row % $batchsize == 0):
echo "<script> senddata('minpoints$row.csv'); </script>";
endif;
$row++;
}
fclose($file);
fclose($handle);
}
} else {
echo "Only CSV files are allowed.";
}
//alert once done.
echo "<script> alert('CSV imported!') </script>";
} ?>
senddata.php :
<?php
include('config.php');
$data = $_POST['file'];
$handle = fopen($data, "r");
$test = file_get_contents($data);
// print_r($test);die;
if ($handle) {
$counter = 0;
//instead of executing query one by one,
//let us prepare 1 SQL query that will insert all values from the batch
$sql ="INSERT INTO table_test(name,contact_number) VALUES ";
while (($line = fgets($handle)) !== false) {
$sql .= "($line),";
$counter++;
}
$sql = substr($sql, 0, strlen($sql) - 1);
if ($conn->query($sql) === TRUE) {
} else {
}
fclose($handle);
} else {
}
//unlink CSV file once already imported to DB to clear directory
unlink($data);
?>
My Goals are :
Upload huge csv data asynchronusly with complete data
To understand this codes :
--> fwrite($file,$json.PHP_EOL); and
--> senddata('minpoints$row.csv'); ;
The table table_test has an NOT NULL column and the csv has NULL values at some case and that's why is not inserted.
You can make name and contact_number NULL, with
ALTER TABLE table_test MODIFY name your-type(your-number); Columns are nullable by default. As long as the column is not declared UNIQUE or NOT NULL, there shouldn't be any problems.
#owf: - thank you, after i changed the structure table, it works
perfectly. Anyway do you have an idea how to skip the first row
(header) ? I've tried to use IF the $counter > 0 on senddata.php , but
it skips every first counter of each batch
R:
First for all, you need to $flag the first parsed csv to know that it comes with the first row to be skipped.
Add a variable to the ajax that check if is the first csv registered.
So, en ajax.php you know if the csv is the first one or not, based in this method, you can skip the first row of the first batched csv
using this you can skip the just first row of CSV file (header of CSV file) . try that
while (($line = fgets($handle)) !== false) {
if ($_POST['file'] == 'minpoints0.csv' && $counter > 0) {
$sql .= "('$line'),";
}
$counter++;
}

Using jQuery pass data to PHP and retrieve data for display in another page

I'm currently having 2 pages that is "index.php", "retrieve_search_forklift.php" and "search_forklift.php".
I try to passing the "txtSearch" input from index.php using jQuery $.post method to "retrieve_search_forklift.php" for execute the select query and echo the $output.
In "search_forklift.php" will use a function to load the "retrieve_search_forklift.php" when page is load and display the $output in a table.
Index.php
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
//alert(data);
window.location.replace("search_forklift.php");
})
}
});
Retrieve_search_forklift.php
<?php
require('../database_connection.php');
if($txtSearch = $_POST['txtSearch']){
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT f_brand, f_ftype, f_image, f_code, f_description, f_sale, f_rental FROM tblforkliftdetail WHERE f_brand='Toyota'";
$result = mysqli_query ($mydatabase, $query);
$counter = 0;
while($info = mysqli_fetch_array( $result ))
{
if( $counter % 3 == 0 )
$output .= "<tr>";
$output .= "<td style='background-color:yellow; '><img src=".$info['f_image'] ." width=210px height=210px ></img></p></td>";
$output .= "<td style='background-color:black;'>";
$output .= "</td>";
if( $counter % 3 > 1)
$output .= "</tr>";
$counter++;
}
echo $output;
}
#mysqli_close($mydatabase);
?>
Search_forklift.php
$(document).ready(function(){
loadsearchtblForklift();
});
function loadsearchtblForklift(){
$('#tblsearchForklift').load('php/retrieve_search_forklift.php');
}
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
I shall simplify this.
You are making a request from A to B; then asking C to show the data that B has generated earlier. This boy, is not possible unless you store the data of B somewhere(DB/file system).
why?
A --> B is a separate request and C --> B is separate. The server does not know that it has to store the data for future request use. You have to change the approach to fulfill this logic.
My Suggestion -
Discard 'Search_forklift.php' and directly show the results in the 'index.php' page directly.
changed index.php file
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
$('#tblsearchForklift').html(data);
})
}
});
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
Or, store the result of 'Retrieve_search_forklift.php' in a txt file or into a CLOB column in database with a session key and retrieve it using the same key to display in the 'Search_forklift.php'.
This approach shall ensure that, the person after you who is going to curse everyday of their life maintaining it. May be you yourself may do that after an year or two. :) Don't get me wrong here. but i just want to make you understand the way web and programming life works.
EDIT: reading again, i got another approach (bad) idea. You can do this in one more way.
Once your ajax call in index.php is returned, POST the results to the 'Search_forklift.php' page and in there just say
<table id="tblsearchForklift"><?php echo $_POST[results]; ?></table>

Javascript in while loop not changing anything until the loop finished

I have 2 seperate files.
The iframe executes the changePercent command in the parent window, but it doesn't change the number instantly, it is only changed after the loop finished. Is there any way to fix this? Need this for a progress bar thingy.
Thanks in advance!
This is the file I open in my browser
<span id="test">1</span><br />
<iframe src="script.php?league=Nemesis"></iframe>
<script type="text/javascript">
function changePercent(val) {
document.getElementById("test").innerHTML=val;
}
</script>
This is the embedded iframe
<?php set_time_limit(0);
include('../assets/includes/functions.inc.php'); ?>
<?php
$i = 0;
$step = 200;
$end = 15000 - $step;
$league = $_GET['league'];
$found = false;
$status = false;
while ($found == false && $i < $end) {
if($i < $end) { $i = $i + $step; }
$ladder = file_get_contents("http://api.pathofexile.com/ladders/".$league."?limit=".$step."&offset=".$i);
$ladder = str_replace('"online":false', '"online":"no"', $ladder);
$ladder = str_replace('"online":true', '"online":"yes"', $ladder);
$json = json_decode($ladder, true);
foreach ($json['entries'] as $address) {
if($address['online'] = "yes") {
$status = true;
// do something
}
}
?>
<script type="text/javascript">
parent.changePercent('<?php echo $i ?>');
</script>
<?php
}
?>
php is a server side language. when the php runs the while loop, that means the browser is still waiting for page data, and it will be sent to the browser only when the php is finished.
in your changePercent you have a php code that is located AFTER the while loop, so it will run the while loop before it can evaluate the php inside the changePercent
so there is no "fix", you should just learn the basics of web programming
You're exiting out of the PHP loop when you use ?> try the following code segment.
echo '<script type="text/javascript"> parent.changePercent(' . $i .'); </script>';
This will tell PHP to print out that line for each time your loop executes through.

invoking jquery in php loop

I am new to php,jquery and json.
I am using all of it in my new website.
My problem is i need to divide my html page into 4 parts as divs(north,south,east,west) and display a pie chart in each div, drawn from a jquery/javascript.
I have added a foreach loop for each zone like north,south,east,west.
and i have set the data needed by jquery/php script in session.
But i see that script executes only at the end of for loop and draws the pie chart only in the fourth div.
I want to know the syntax of how i can invoke the script for every iteration of the php loop.
Request your help.
<?php
$customerSelected = "IBL";//change this to actual selected customer
$zoneArray = array(1,2,3,4);
$_SESSION['customerSelected']=$customerSelected;
foreach($zoneArray as $zone){
$_SESSION['zone']=$zone;
$quadrantName = '';
if($zone == 1){
$quadrantName = 'firstQuadrantNorth';
}else if($zone == 2){
$quadrantName = 'secondQuadrantSouth';
}else if($zone == 3){
$quadrantName = 'thirdQuadrantEast';
}else if($zone == 4){
$quadrantName = 'fouthQuadrantWest';
}
$_SESSION['quadrant']=$quadrantName;
?>
<div id="<?=$zone?>" style="height:250px;width:49.7%;float:left; border:1px solid #CCC;">
<div id="<?=$quadrantName?>" style="min-width:50%; height:100px;text-align:left"></div>
<script src="scripts/piechartsims.js?v=<?=$cachebuster; ?>"></script>
<div style="min-width:50%;height:140px;text-align:center;align:center;overflow:auto;">
<?php
include('LastCommunicatedInc.php');
?>
</div>
</div>
<?php
}
?>
`

Grabbing PHP info and placing inside divs

I'm not sure if this is possible, but I'm trying to take the value of $css_color and set it as the hex value in the div. Also with the $x and $y values.
Essentially, I'm attempting to grab the $x$y info and the hex code value from an image and matching it to an array of color values I have in formatted_colors.js then rebuilding the "image" as divs with the background color as testing.
Example of my formatted_colors.js array var colors = []; colors["000000"] = "black"; colors["100000"] = "black";
Here is a snippet:
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script src="formatted_colors.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//iterate through pixels and match rounded color to array in formatted_colors.js
<div class="rounded_color" hex="<?php $css_color ?>" xy="<?php $x.$y ?>"</div>
<div id="<?php $x.$y ?>"></div>
$(document).ready(function() {
$(".rounded_color").each(function(){
var google_color = getColor($(this).attr("hex"));
$('#'+$(this).attr("id")).html(google_color);
$('#'+$(this).attr("id")).css('background-color:', google_color);
})
// get name of color function from formatted_colors.js
function getColor(target_color){
if (colors[target_color] == undefined) { // not found
return "no match";
} else {
return colors[target_color];
}
} // end getColor function
)} // end ready function
</script>
And here is my entire code: http://pastebin.com/A4tMsn2C
Try <?php echo $x.$y ?> instead (and similar for your other blocks). Or, if you've got shorttags enabled <?= $x . $y ?>. Your version is simply doing a concatentation and throwing out the results. You need to echo out the results of whatever you're doing inside the PHP block.

Categories