jQuery animate Problems - php

So here are my functions,
function getOffset(el){
var _x = 0;
var _y = 0;
while ( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function makeSeeds(id){
var seedmaker = getOffset(document.getElementById('seedmaker'));
$("#"+id).animate({
"left":seedmaker.left
}, 2000, function(){
$("#"+id).animate({
"top":seedmaker.top
}, 1000, function() {
$(this).hide("explode",{pieces:52},1000);
$("#"+id+"seeds").animate({
"opacity":"toggle",
"top":"+=10px",
"left":"+=30px"
}, 1000);
$("#dialog").html("Successfully created one "+id+" seed!");
$("#dialog").dialog();
$("#"+id+"seeds").hide("slow");
});
});
}
http://dreamsofrenewal.us/jquery.html works just fine, but when I use it on another page with more items, it animates down to the bottom right of the page.
Here's the PHP for that page:
$id = 0;
$c = "<div id='dialog' style='display:none;'></div><table width='95%' class='ti' cellpadding='4' cellspacing='1' style='margin:10px;margin-left:auto;margin-right:auto;'>";
$sql = mysql_query("SELECT * FROM `received` WHERE `uid` = '".$this->uid."'");
while ($row = mysql_fetch_array($sql)) {
$c .= "<tr><td>";
for ($x = 0; $x < $row["amount"]; $x++) {
$i = $id++;
$c .= "<img style='position:absolute;' src='images/crops/" . $this->uI("itembase", $row["thing"], "sprite") . "' border='0' alt='image' id='" . $i . "' onclick='makeSeeds(" . $i . ");' />";
}
$c .= "</td></tr>";
}
$c .= "</table>";
$finalid = $id;
$c .= "<script type='text/javascript'>
$(document).ready(function(){
var ids='";
for ($x = 0; $x < $finalid; $x++){
$c .= "#" . $x . ",";
}
$c .= "';
$(ids).click(function(){makeSeeds(this.id);});
});
</script>";
$sql2 = mysql_query("SELECT * FROM `bought` WHERE `uid` = '".$this->uid."'");
while ($row2 = mysql_fetch_array($sql2)) {
if ($this->uI("itembase",$row2["itemid"],"type") == "crops") {
$c .= "<img src='images/crops/" . $this->uI("itembase", $row["itemid"], "sprite") . "' border='0' alt='image' id='".$row["itemid"]."' />";
}
}
for ($x=0; $x < $finalid; $x++){
$c .= "<img src='images/seeds/turnip.png' id='" . $x . "seeds' style='display:none; position:absolute; left:10px;' border='0' alt='seeds' />";
}
$c .= "<img src='images/makers/seed.png' alt='seedmaker' id='seedmakerx' style='position:absolute; left:10px;' /></div>";
return $c;
If you need more info, I can put up a test page with that PHP for you..
Thanks in advance!
Test with PHP: http://dreamsofrenewal.us/phptest.php
It works fine, it's just duplicating itself? And if you click too many in a row, it lags browser really bad? Any idea how to make it work faster?
//remade this because I said I fixed when I didn't :-X

Well, your browser will lag anyway. If you want to get rid of lag, you have to group animating objects. Exmp.: When at one time user clicks many items, you group them into one DIV(object), and animate object, but not each item. There is actualy no way to animate it smoother over browsers. There is another solution, that you can not move item, but increse size, and then hide it or something like that. Or just make your own animation with less steps.
But the BEST solution is to use canvas, or if you making this game for your own education, make it with WebGL.
Best canvas game, tought

Related

PHP loop outputting duplicates

public function select(){
$rows = [];
$connection = $this->connect();
$result = $connection->query("SELECT username FROM users");
while ($row = $result->fetch_assoc()){
$rows[] = $row;
}
$userlist = 0;
foreach($rows as $username){
$userlist .= $username['username'];
}
$get_rankings = [1,2,3,4];
$get_image_path = "images/";
$total = 0;
for ($x = 0; $x < count($get_rankings); $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $userlist . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}
echo $path;
}
I'm trying to output a simple ranking but using the number index as images to display them.
In the past i've tried to do something similar but couldn't figure out how to match player it with images on the side.
The output im getting is this:
It's outputting each entry 4 times(I get why, its in a loop) but I can't figure out the correct solution to write it outside of a loop or properly
The desired output is:
My DataBase reads as:
[id][username][password]
If there is an easier solution, i'm all ears. I don't know how to approach this.
There's no need for $userlist. Output the username from $rows[$x].
$path = "";
$max = min(count($rows), count($get_rankings));
for ($x = 0; $x < $max; $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $rows[$x]['username'] . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}

PHP+Jquery - displaying values in a table

Good evening.
This construction displays the values in a table that sorts them in alphabetical order.Those for example, if you click on the D link, only the names with letter D should be shown, and so on.
PHP code:
<?php
include ('engine/api/api.class.php');
$table = 'dle_post';
$fields = 'xfields';
$where = 'approve=1';
$multirow = 1;
$start = 0;
$limit = 0;
$xfield = 'actor';
$time = '14000';
$tr_new = 0;
$xfields = $dle_api->load_from_cache ($fields, $time, $xfields);
if( !$xfields ) {
$xfields = $dle_api->load_table ($table,$fields,$where,$multirow,$start,$limit);
$dle_api->save_to_cache ( xfields, $xfields);
}
$stack = array();
foreach($xfields as $value){
if($value[xfields]){
$row = xfieldsdataload($value[xfields]);
if($row[$xfield]){
$rowdata = explode( ",", $row[$xfield]);
foreach($rowdata as $value){
if($value){
$value = trim($value);
array_push($stack, $value);
asort($stack);
}
}
}
}
}
$stack = array_count_values($stack);
foreach($stack as $key => $count){
if($tr_new === 0){
echo '<tr class="new">';
}
echo "<td class='blok'>";
echo "<a href=/" . $xfield . "/";
echo $key;
echo " target='_blank' rel='noopener'>";
echo $key;
echo "</a>";
echo "<span>";
echo "(" . $count . ")";
echo "</span>";
echo "</td>";
$tr_new++;
if($tr_new === 1){
echo '</tr>';
$tr_new = 0;
}
}
JQuery:
$(function () {
var _alphabets = $('.alphabet > a');
var _contentRows = $('#countries-table tbody tr');
_alphabets.click(function () {
var _letter = $(this), _text = $(this).text(), _count = 0;
if(_text == 'all') _text = '.';
_alphabets.removeClass("active");
_letter.addClass("active");
_contentRows.hide();
_contentRows.each(function (i) {
var _cellText = $(this).children('td').eq(0).text();
if (RegExp('^' + _text).test(_cellText)) {
_count += 1;
$(this).fadeIn(400);
}
});
});
});
In page:
<div class="alphabet">
<a class="first" href="#">All</a>
A
B
C
...
<a class="last" href="#">Z</a></div>
<div id="conutries">
<table id="countries-table">
<tbody>
{include file="/code.php"}
</tbody>
</table>
</div>
</div>
Everything works fine, but I encounter such a problem - it turns out correctly to output only one value in one line tr ...
When I try to put a 4 td values to the tr line if($tr_new === 4) - they are not sort by alphabetically, they just displayed like this:
Whats wrong? What need to make this code work fine for me?
Thank you in advance for your help!

Random color and div width not working

Here is my code:
<?php
// Returns a random RGB color (used to color the vote bars)
function getRandomColor2()
{
$r2 = rand(128,255);
$g2 = rand(128,255);
$b2 = rand(128,255);
$color2 = dechex($r2) . dechex($g2) . dechex($b2);
echo "$color2";
}
echo "<table id=\"tblResults2\" align=\"center\">";
// Get max vote count
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$maxvotes2 = 0;
$pollitems2 = $doc->getElementsByTagName("pollitem");
foreach( $pollitems2 as $pollitem2 )
{
$votes2 = $pollitem2->getElementsByTagName("votes");
$vote2 = $votes2->item(0)->nodeValue;
$maxvotes2 = $maxvotes2 + $vote2;
}
// Generate the results table
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$pollitems2 = $doc->getElementsByTagName("pollitem");
foreach( $pollitems2 as $pollitem2 )
{
$entries2 = $pollitem2->getElementsByTagName("entryname");
$entry2 = $entries2->item(0)->nodeValue;
$votes2 = $pollitem2->getElementsByTagName("votes");
$vote2 = $votes2->item(0)->nodeValue;
$tempWidth2 = $vote2 / $maxvotes2;
$tempWidth2 = 300 * $tempWidth2;
$votepct2 = round(($vote2 / $maxvotes2) * 100);
echo "<tr><td width=\"45%\" class=\"polls\">$entry2</td>";
echo "<td width=\"35%\" class=\"resultbar\"><div class=\"bar\" style=\"background-color: ";
getRandomColor2();
echo "; width: $tempWidth2 px;\">$votepct2%</div></td><td class=\"each_vote\" width=\"20%\">($vote2 votes)</td></tr>";
}
echo "<tr><td width=\"45%\" class=\"total\" colspan=\"3\">Σύνολο ψήφων: $maxvotes2</td>";
echo "</table>";
?>
My issue is that when I call it, everything works BUT:
I get no color
All my DIVs that display the % are the same width instead of $tempWidth2
Is it easier to display fixed (different) colors for each div?
Thank you
Change:
echo "$color2";
to:
echo "#$color2"; // added #, fixes colors
...and change:
echo "; width: $tempWidth2 px;\">$votepct2%</div></td><td class=\"each_vote\" width=\"20%\">($vote2 votes)</td></tr>";
...to:
echo "; width: {$tempWidth2}px;\">$votepct2%</div></td><td class=\"each_vote\" width=\"20%\">($vote2 votes)</td></tr>";
// removed a space, wrapped var in {}, fixes widths
...although you would do much better in terms of readability to return a string from your function, like this:
function getRandomColor2()
{
$r2 = rand(128,255);
$g2 = rand(128,255);
$b2 = rand(128,255);
$color2 = dechex($r2) . dechex($g2) . dechex($b2);
return "#".$color2;
}
// ...
echo "<tr>"
. "<td width=\"45%\" class=\"polls\">{$entry2}</td>"
. "<td width=\"35%\" class=\"resultbar\">"
. "<div class=\"bar\" style=\"background-color: ".getRandomColor2()."; width: {$tempWidth2}px;\">{$votepct2}%</div>"
. "</td>"
. "<td class=\"each_vote\" width=\"20%\">({$vote2} votes)</td>"
. "</tr>";

creating a moustache.js html template using JSON

I just learned about moustache.js and i am attempting to create an HTML template. However, the documentation is a bit hard to decipher. I found a good site that explains partials (which I believe I will need). I was hoping someone might be able to just 'get me started' on how I would need to do this.
I have a php file that I need to convert to the template:
PHP:
<div id='board'>
<?php
if ($threads)
{
$count = count($threads);
$perpage = 17;
$startlist = 3;
$numpages = ceil($count / $perpage);
if ($page == 'home') {$page = 1;}
$threadstart = ($page * $perpage) - $perpage;
$i = 0;
echo "<table class='board'>
<tr>
<th width='5%'><img src='".base_url()."img/board/icons/category_icon.png' alt='category_icon'/></th>
<th width='5%'>Tag</th>
<th width='50%'>Subject</th>
<th width='7.5%'>Author</th>
<th width='7.5%'>Replies/Views</th>
<th width='15%'>Last Post</th>
</tr>";
foreach ($threads as $list)
{ $i++;
$thread_owner = $this->thread_model->get_owner($list['owner_id']);
$thread_id = $list['thread_id'];
$query = $this->db->query("SELECT f.tag FROM filter_thread AS ft
INNER JOIN filter AS f ON ft.filter_id = f.filter_id
WHERE thread_id = $thread_id");
$result = $query->result_array();
$trunc_body = $this->thread_model->get_reply_summary($thread_id);
$filter = "";
$filter2 ="";
$ent = "entertainment";
foreach ($result as $string)
{
if ($string['tag'] == $ent) {
$filter2 .= "<div id='entertainment'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/entertainment_icon.png' title='Entertainment' alt='Entertainment'/>";
$filter2 .= "</p></div>";
} else {
$filter2 .= "<div id='misc'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/misc_icon.png' title='Misc' alt='Misc'/>";
$filter2 .= "</p></div>";
$filter .= " [".$string['tag']."]";
}
}
if (!$result) { $filter = "" AND $filter2 =""; }
if ($i > $threadstart AND $i <= $threadstart + $perpage)
{
echo "<tr>";
echo "<td>".$filter2."</td>";
echo "<td>".$filter."</td>";
echo "<td title='".$trunc_body['0']['body']."'>".ucfirst($list['subject'])."<div id='filter'><p></p></div></td>";
echo "<td><p>".$thread_owner."</p></td>";
echo "<td align='right'>Replies: ".$list['replies_num']."<br>Views: ".$list['views']."</td>";
$owner = $this->thread_model->get_owner($list['last_post_id']);
echo "<td>".$owner." <br>".$list['replystamp'] ."</td></tr>";
}
}
echo "</table>";
echo "<br>";
echo "Current Page: $page | ";
echo "Page: ";
for ($n = 1; $n < $numpages+1; $n++)
{
echo "<a href=".base_url()."main/home/$n>$n</a> | ";
}
}
?>
</div>
And here is the AJAX
$(function() {
$('#all').addClass('ui-selected')
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters },
success: function(data){
var template = "<div id ='board'>TESTING{{#body}}<table>";
var partials = "{{#subject}}";
//for (i=0 ; i< data.length ; i++)
//{html += "<tr><td>" + data[i].subject + "</td><td>" + data[i].body + "</td></tr>";}
//html += "</table></div>";
var html = Moustache.to.html(template, data, partials);
$('#board').html(html);
}
});
}
});
Im not sure how to navigate through the JSON array with moustache..and as it is, it does not update the page, though the commented out parts DO.
Thanks in advance!
First of all if you are receiving a json string you will need to to parse it (use $.parseJSON(data))
Once you have the data parsed you need to loop throught the JSON attributes.
For example:
If JSON has the following: body: {content: [dataObj:{data:'a'}, dataObj[data:'b']]}
do
<div>{{#body}}<div>
<div>{{#content}}<div>
<div>{{#dataObj}}<div>
<span>{{data}}<span>
If you are using partial, you will need to call them inside the main template.
Check the moustache5 documentation, it has improved a lot.

php report is very slow and crashes in firefox

I have a report that runs and returns 366 records, each containing a thumbnail that is 104 x 80 px. The issue is that the report runs very slowley even though I increased the memory size.
ini_set('memory_limit', '128M');
ini_set('max_execution_time','600');
After writing the SQL query I generate the table items here
generate_table_items($query_all_items);
This then runs through and checks for the image in the columns
function generate_table_items($query){
$columns = array();
$resultset = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$columncount = 0;
$rowcost = 0;
$rowsale = 0;
while ($row = mssql_fetch_assoc($query)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th scope="col" >'.implode('</th><th scope="col" >',get_column_name($columns)).'</th></tr>';
$columncount = sizeof(array_keys($row));
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>',report_image_check($row)).'</td></tr>';
if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$colspan = (count($columns)-2);
echo "<tr><th scope='row'>Documents</th><td colspan='$colspan' >";
$PKID = $row['ID'];
if($row['SumOfTotalCost'] || $row['SumOfSalePrice']){
$rowcost += $row['SumOfTotalCost'];
$rowsale += $row['SumOfSalePrice'];
$get_total = true;
}
$query_docs = mssql_query("select documents.* from dbo.documents where documents.Antiquities_id = $PKID") or die ('get docs query failed ' . mssql_get_last_message());
while($row_docs = mssql_fetch_assoc($query_docs)){
$document = "../documents/" . $row_docs['document'];
echo "<a href='$document' title='opens in a new window' target='_blank' >" . $row_docs['document'] . "</a> | ";
} // End while (list docs)
mssql_free_result($query_docs);
echo "</td></tr>";
myflush();
} // End if all items and all items by value report
} // End While
echo '<tr>';
for($i=0;$i < $columncount-4;$i++){
echo '<td> </td>';
}
echo '<td>Total Cost '. $rowcost.'</td>';
echo '<td>Total Sale '. $rowsale.'</td>';
echo '<td>Total Calculated Difference '. ($rowsale-$rowcost).'</td></tr>';
} // End function
function get_column_name($columns){
$newcol = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$thecount = 0;
foreach($columns as $col) {
if($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
// Don't list the PK
} else {
$newcol[] = '<img id="'.$col.'" src="../images/icons/arrow_down.png" alt="click to sort by" onclick="sortby(\''.$col.'\');" />' . $col;
}
$thecount++;
}
/*if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$newcol[] = "documents";
}*/
return $newcol;
}
function report_image_check($row){
global $base_url, $uploaded_images_folder;
$newrow = array();
$imageext = array();
$imageext[0] = ".jpg";
$imageext[1] = ".png";
$imageext[2] = ".gif";
$imageext[3] = ".tiff";
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$PKID = 0;
$thecount = 0;
foreach($row as $rn) {
if(in_array(strtolower(substr($rn,-4)),$imageext)){
$small_img_ext = substr($rn,-4);
$small_img = substr($rn,0,strripos($rn,"."));
$small_img = $small_img . '_140_105' . $small_img_ext;
$newrow[] = '<a href="' . $base_url . $uploaded_images_folder . '/' . $small_img . '" title="click to zoom on image" target="_blank" ><img src="' . $base_url . $uploaded_images_folder . '/' . $rn . '" alt="" width="50px" height="50px" /></a>';
} elseif($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$PKID = $rn;
} elseif($thecount == 2 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='../index.php?template=10&PKID=$PKID' target='_blank' >$PKID (click to view)</a>";
} else {
$newrow[] = $rn;
}
$thecount++;
myflush();
}
/*if (in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='#&PKID=$PKID' target='_blank' >Documents (click to view)</a>";
}*/
return $newrow;
} // End function
//// Flushing function
function myflush(){
ob_implicit_flush();
ignore_user_abort();
}
Can anyone see an issue with this code or see why it would take so long or why it crashes firefox? Would printing to pdf function work better?
It'll take a long time because you're nesting SQL queries... executing a second SQL query for every result that has been returned by the first query.... Doing a single query with a JOIN should help performance significantly.
Printing to PDF would almost certainly be slower: you'd eithe rneed a lot of code to position everything correctly in the report yourself, or to use one of the libraries that can take HTML and render it to a PDF (as you're already generating HTML anyway at the moment, this would be additional processing)

Categories