How would I animate an auto-updating mysql query result? - php

Basically, how would I make an auto-updating mysql query result animated using jquery? I would want it to look like a newsfeed that is animated and slides down when a result it added? How difficuilt would this be to achieve and what would I use to do it?
Thanks,
Cameron

First you need some JS, PHP and HTML skill.
JAVASCRIPT:
function create_ajax()
{
try
{
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
return ajaxRequest;
}
You need this function in your HTML file, to start the message service:
function StartUp()
{
/** Jquery **/
setTimeout(function() {$('#message').fadeOut('fast');}, 5000);
UserLogService();
}
This function helps to connect to PHP:
function MessageService()
{
setTimeout('MessageService()', 60000);
var ajaxRequest;
ajaxRequest=create_ajax();
ajaxRequest.onreadystatechange =
function()
{
if(ajaxRequest.readyState == 4)
{
message = ajaxRequest.responseText.split(';');
if (message[0])
{
headMessageDisplay(message[0], message[1]);
setTimeout('headMessageNoDisplay()', 30000);
}
}
}
ajaxRequest.open("GET", "xxx.php", true);
ajaxRequest.send(null);
}
In your PHP get the messages:
if ($msg)
{
$this->Show($msg);
exit();
}
PHP: This shows the message from PHP:
private function Show($msg = null)
{
for ($i = 0; $i < count($msg); $i++)
{
$error = $this->html;
$error = str_replace('{MESSAGE}', $msg[$i], $error);
$error = str_replace('{TYPE}', error, $error);
$error = str_replace('{DISPLAY}', 'block', $error);
$this->message .= $error;
}
print $this->message;
}
This makes the message itself:
$r = $_REQUEST["sql"]->Query("SELECT m.id, m.message, t.name as type FROM db_table_message m JOIN db_table_messagetype t ON (t.id = m.type) WHERE m.processing = '0' AND m.user_id = '".$_REQUEST["user"]->Id."'
AND m.date != '0000-00-00 00:00:00' AND m.date <= DATE_SUB(NOW(), INTERVAL -1 MINUTE) LIMIT 1");
$a = $_REQUEST["sql"]->GetRecord($r, 0);
if (!$a["id"])
{
$r = $_REQUEST["sql"]->Query("SELECT m.id, m.message, t.name as type FROM db_table_message m JOIN db_table_messagetype t ON (t.id = m.type) WHERE date = '0000-00-00 00:00:00' AND m.processing = '0' AND m.user_id = '".$_REQUEST["user"]->Id."' LIMIT 1");
$a = $_REQUEST["sql"]->GetRecord($r, 0);
}
if ($a["id"])
{
$_REQUEST["sql"]->Query("UPDATE db_table_message SET processing = '1' WHERE id = '$a[id]'");
}
else
{
$r = $_REQUEST["sql"]->Query("SELECT m.id, m.message, t.name as type FROM db_table_message m JOIN db_table_messagetype t ON (t.id = m.type) WHERE m.user_id = '0' LIMIT 1");
$a = $_REQUEST["sql"]->GetRecord($r, 0);
}
$this->Show($a["message"], $a["type"]);
}
private function Show($message = null, $type = null)
{
if ((!$message) || (!$type)) return false;
switch($type)
{
case "information":
$type = information;
break;
case "warning":
$type = warning;
break;
case "error":
$type = error;
break;
}
print "$message;$type";
Use a PHP Class to get the message from the database... There are many things needed to do this. I nearly forgot to get the old messages from the database on page load by php.
Then, if everything works, add:
ANIMATION
$("selector").fadeIn(slow);
If you want to do the animation with jQuery. :) The animation itself is the last thing you have to worry about. :)

I'll throw my oar in here although this is a similar solution to Dae except using jQuery templates and JSON. I don't work with php myself but creating JSON doesn't seem too difficult with json_encode()
jsFiddle Example

Broadly:
Create a PHP page that returns the results of the MySQL query.
Periodically load() that page with Javascript from the containing page.
Update the contents of the containing element if a difference is found.
Here's a very brief outline. Initially, let's get the results.
// results.php
$sql = "SELECT * FROM `tbl` LIMIT 10 ORDER BY date_created DESC";
if(!$query = mysql_query($sql))
trigger_error(mysql_error());
while($result = mysql_fetch_assoc($query))
print_r($result);
Then make a page to show them.
// index.html
<script type="text/javascript">
function loadResults() {
$('#results').fadeTo('fast' , 0).load('results.php').fadeTo('fast' , 1);
}
$(document).ready(function() {
loadResults();
var interval = self.setInterval(loadResults(), 10000);
});
</script>
<div id="results"></div>
Untested.

Related

vTiger Custom Field Validation beforesave

I have created a custom module on vTiger 6.5.
I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.
Please see my code below. Thanks!
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {}
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave.final') {}
if($eventName == 'vtiger.entity.aftersave') {
}
}
}
}
?>
After doing some searching around and looking at other peoples event handlers I managed to solve this by changing:
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
to
if($eventName == 'vtiger.entity.beforesave') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
Now I want to see if I can display the message and then give a link to go back to the entity module with all the fields still full.
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database
Here is an example:
In your Edit.js:
donCache : {},
checkDon : function(details) {
// alert("checkOverlap");
var aDeferred = jQuery.Deferred();
var params = {
'module' : 'Affectations',
'action' : "checkAffectAmount",
'mode': 'CtrlAffectAmount',
'recordId' : details.don,
'montant' : details.montant
}
AppConnector.request(params).then(
function(data) {
if (data.success == true) {
// console.log(data.result);
var statut = data.result.statut;
var reste = data.result.reste;
if(statut == "error"){
aDeferred.reject(data);
}else {
aDeferred.resolve(data);
}
}
},
function(error,err){
aDeferred.reject();
}
);
return aDeferred.promise();
},
registerRecordPreSaveEvent : function(form) {
var thisInstance = this;
if (typeof form == 'undefined') {
form = this.getForm();
}
form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
var check = false;
var recordId = jQuery('input[name="record"]').val();
if (!recordId || recordId) {
var montant_affectation = jQuery("input[name='affectations_montant']").val();
var don_id = jQuery("input[name='affectations_potentialid']").val();
var params = {};
if (!(check in thisInstance.donCache)) {
thisInstance.checkDon({
'montant' : montant_affectation,
'don': don_id
}).then(
function(data){
thisInstance.donCache[check] = data['success'];
form.submit();
},
function(data, err){
thisInstance.donCache[check] = data['success'];
var reste = data.result.reste;
var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure de ")+ reste +app.vtranslate(" Euros au montant du don");
Vtiger_Helper_Js.showPnotify(msg);
delete thisInstance.donCache[check];
}
);
} else {
delete thisInstance.donCache[check];
return true;
}
e.preventDefault();
}
})
},
The PHP part in modules/isa/actions:
<?php
/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/
class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {
function __construct() {
$this->exposeMethod('CtrlAffectAmount');
}
public function checkPermission(Vtiger_Request $request) {
$moduleName = $request->getModule();
$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
$permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());
if(!$permission) {
throw new AppException('LBL_PERMISSION_DENIED');
}
}
public function process(Vtiger_Request $request) {
$mode = $request->getMode();
if(!empty($mode) && $this->isMethodExposed($mode)) {
$this->invokeExposedMethod($mode, $request);
return;
}
}
function CtrlAffectAmount(Vtiger_Request $request){
global $adb,$log;
$log->debug("ALTAIR CtrlAffectAmount OK");
$recordId = $request->get('recordId');
$montant = $request->get('montant');
// $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
$query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
$sommeAffectation = $adb->query_result($query,0,"sommeaffectation");
$query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
$montantDon = $adb->query_result($query,0,"amount");
if ( ($sommeAffectation + $montant) == $montantDon) {
$statut = "ok";
$reste = "";
} else if( ($sommeAffectation + $montant) > $montantDon) {
$statut = "error";
$reste = ($sommeAffectation + $montant) - $montantDon;
}
$value = array('statut'=>$statut, 'reste'=>$reste);
$response = new Vtiger_Response();
$response->setEmitType(Vtiger_Response::$EMIT_JSON);
$response->setResult($value);
$response->emit();
}
}
Oh. you have 1 invalid error here. please change:
if($eventName == 'vtiger.entity.beforesave') {
$currentAmount = $entityData->get('currentamount');
if($currentAmount > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}

AS3 not recieving myStatus from php login page

I am not receiving the myStatus when retrieving it from the php login. I get p_id and full name but not the status. I am parsing it to separate out the & but keep getting a null result from login. section 6 and section 7 are the areas I think I am having issues can anyone help?
login AS3
package {
import flash.display.MovieClip;
import flash.text.*;
import flash.events.*;
import flash.ui.Keyboard;
import flash.net.*;
import MainDocument;
public class Login extends MovieClip {
public function Login() {
// constructor code
// modify existing text boxes
login_txt.tabEnabled = true;
login_txt.tabIndex = 1;
login_txt.border = true;
login_txt.borderColor = 0xAAAAAA;
login_txt.background = true;
login_txt.backgroundColor = 0xFFFFDD;
pwd_txt.tabEnabled = true;
pwd_txt.tabIndex = 2;
pwd_txt.border = true;
pwd_txt.borderColor = 0xAAAAAA;
pwd_txt.background = true;
pwd_txt.backgroundColor = 0xFFFFDD;
login_btn.tabEnabled = true;
login_btn.tabIndex = 3;
//add button event listeners
login_btn.addEventListener(MouseEvent.MOUSE_UP, doLogin);
login_close_btn.addEventListener(MouseEvent.MOUSE_UP, doClose);
addEventListener(KeyboardEvent.KEY_DOWN, onEnter);
} // end construtor
private function onEnter(e:KeyboardEvent):void{
// nothing yet
if(e.keyCode == Keyboard.ENTER){
trace("User presses keyboard ENTER key");
doLogin(null); // must be null to meet the need for a parameter
}// end if
}// end function
// SECTION 1 – This is a function we need for removing extra whitespace coming from CWP server
function trimWhitespace($string:String):String {
if ($string == null) {
return "";
} //end if
return $string.replace(/^\s+|\s+$/g, ""); // see regular expressions
} // end function
private function doLogin(e:MouseEvent):void{
//trace("User presses OK button");
// SECTION 2 – URL request variable declared with path to server script
var req:URLRequest=new URLRequest(MainDocument.localPath + "login.php");
req.method = URLRequestMethod.POST;
// SECTION 3 – Upload variables are named as URL variables
var vars:URLVariables=new URLVariables();
vars.login = login_txt.text;
vars.pwd = pwd_txt.text;
req.data = vars;
// SECTION 4 – The URL Loader class instance is set to perform the HTTP POST
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
// SECTION 5 – listeners are added for both the HTTP status and COMPLETE
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,onHTTPStatus);
loader.addEventListener(Event.COMPLETE, retrieveData);
// SECTION 6 – The complete handler function is embedded within the doLogin() function
function retrieveData(e:Event):void {
// For the CWP server we must parse our own incoming data
var rawString:String = trimWhitespace(unescape(e.target.data));
var stArray:Array = rawString.split("&"); //split on ampersand character
trace("retrieve data");
for(var i:uint; i<stArray.length; i++){
stArray[i] = trimWhitespace(stArray[i]);
var pair:Array = stArray[i].split("=");
pair[0] = trimWhitespace(pair[0]);
switch (pair[0]){
case "myStatus":
var ms:String = trimWhitespace(pair[1]); // status data value
break;
case "p_id":
var id:int = int(trimWhitespace(pair[1])); // player id
break;
case "fullname":
var fn:String = trimWhitespace(pair[1]); // fullname
break;
default: // this is all the other junk---> dump
//do nothing
} // end switch
} //end for
// SECTION 7 – A switch statement to deal with cases of myStatus
switch (ms){
case "NOTOK" :
MainDocument.doc.showMsg("There is a communication problem\nTry Again!");
break;
case "OK" :
if(fn != "INVALID"){
MainDocument.doc.showMsg("Welcome " + fn);
//MainDocument.player_id = id;
//MainDocument.player_name = fn;
MainDocument.doc.removeLogin();
MainDocument.doc.turnOffButton("both");
//MainDocument.doc.enable_chat_button();
//MainDocument.doc.activateConsole();
////////////////////////
// start game here
////////////////////////
}else{
MainDocument.doc.showMsg("Login or password is incorrect. Try again, or \nif you are not a member, please register");
MainDocument.doc.turnOnButton("register");
MainDocument.doc.turnOffButton("login");
}
break;
default:
//MainDocument.doc.showMsg("An unknown problem has occured");
} // end switch
} // end function
// SECTION 8 – Handler function for HTTP status – also embedded
function onHTTPStatus(event:HTTPStatusEvent):void {
//trace("HTTP response code " + event.status);
if(event.status!=200){
MainDocument.doc.showMsg("There is an I/O Error #" + event.status);
} // end if
} // end function
} // end function doLogin
private function doClose(e:MouseEvent):void{
// nothing yet
trace("User presses Close button");
MainDocument.doc.showMsg(""); // clears any message
MainDocument.doc.removeLogin();
MainDocument.doc.turnOnButton("both");
}// end function
}//end class
}// end package
login.php
<?php
require_once("settings.inc.php");
// Create vars and load with incoming POST data
$login = $_POST['login'];
if(!isset($login)){
$login = $_GET['login'];
}
$pwd = $_POST['pwd'];
if(!isset($pwd)){
$pwd = $_GET['pwd'];
}
//=========================================================================================
// MAIN
//=========================================================================================
if(!(isset($login) && isset($pwd))){
print "myStatus=NOTOK&dummy=dummy";
}else{
$query = "SELECT `p_id`,`p_name` FROM `player` WHERE `p_login`='$login' AND `p_pwd`='$pwd'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_row($result);
if($row[0] != null && $row[0] != ''){
$p_id = $row[0];
$fullname = trim($row[1]);
$myStatus = $row[2];
print "myStatus=OK&p_id=" . trim($p_id) . "&fullname=" . trim($fullname) . "&dummy=dummy";
}else{
$fullname = "INVALID";
print "myStatus=OK&fullname=" . trim($fullname) . "&dummy=dummy";
} //end else
} //end else
?>

How to insert array values in mysql with a loop

Reading a Textarea with jquery , splitting each line in Array then with ajax posting that array in mysql through php but in results only first value inserted.
Table:
CREATE TABLE IF NOT EXISTS addresses (
id int(8) NOT NULL PRIMARY KEY,
user_id int(8) DEFAULT NULL,
address_value varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Here is Jquery Code :
$('#insertad').click(function(){
var lines = $('#txtArea').val().split('\n');
var phparray = new Object();
for(var i = 0;i < lines.length;i++){
phparray[i] = lines[i]; //store value in object
}
$.post('functions.php?action=insertad', {array1:$.param(phparray)}, function(resp){
$('.text-success').html(resp);
if(resp == 'Added'){
$('.text-success').html('Added Address :');
}
});
});
Here is PHP Code :
if ($action == 'insertad') {
$pieces = explode('&', $_POST['array1']); //explode passed serialized object
$phparray = array();
foreach ($pieces as $piece) {
list($key, $value) = explode('=', $piece);
$phparray[$key] = $value; //make php array
}
$length = count($phparray);
for ($i = 0; $i < 7; $i++) {
$sql = "select address_value from addresses where address_value = '$phparray[$i]'";
$qry = mysql_query($sql);
$numrows = mysql_num_rows($qry);
if ($numrows > 0) {
echo "One Found !!" ;
} else {
$sql = "insert into addresses (address_value) values ('$phparray[$i]')";
$qry = mysql_query($sql);
if ($qry) {
echo "Added";
}
}
}
}
Try this please...
JS:
var $textarea = $('textarea'); // maybe you have to specific your selector!
var textArray = $textarea.val().split("\n"); // this array is already done, your have not todo next for() loop
$.post('functions.php', {
action: 'insertad',
array1: textArray
}, function(results) {
$.each(results, function(reslt) {
if(result === 'Added') {
$('.status').append(result);
}
else {
$('.status').append(result);
}
});
});
PHP:
if($action === 'insertad') {
$results = [];
$input = $_POST['array1'];
foreach($input AS $textLine) {
$escapedTextLine = mysqli_real_escape_string($resource, $textLine);
$result = mysqli_query($resource, 'select address_value from addresses where address_value = "'.$escapedTextLine.'"');
$affectedRows = mysqli_num_rows($result);
if($affectedRows > 0) {
$results[] = 'One Found !!';
}
else {
$result = mysqli_query($resource, 'INSERT INTO `adresses` (`address_value`) VALUES("'.$escapedTextLine .'");
if($result) {
results[] = 'Added!';
}
}
}
return $results; // we return all done results to check this array in ajax response
}
Notice: I wrote the code blind, so maybe you have to make some small changes for e.g. your variables or something like that.
Notice 2: I write the code with mysqli, so you have to rewrite your Database connection setup code.
Please never forget to use mysqli_real_escape_string do something with user contents.

sqlite3 replacement for sqlite_has_more

First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)

Most effective way of data collection?

Let's first get to an important note about my situation:
I have 1 table in my MySQL database with approx 10 thousand entries
Currently, when collecting information from table #1. I collect a total of 20 - 24 rows per page.
Example being:
Q1 : SELECT * FROM table WHERE cat = 1 LIMIT 0,25
R1: id: 1, name: something, info: 12
The PHP file that does these queries, is called by the jquery ajax function, and creates an XML file that that jquery function reads and shows to the user.
My question here is. How do i improve the speed & stability of this process. I can have up to 10 thousand visitors picking up information at the same time, which makes my server go extremely sluggish and in some cases even crash.
I'm pretty much out of idea's, so i'm asking for help here. Here's an actual presentation of my current data collection (:
public function collectItems($type, $genre, $page = 0, $search = 0)
{
// Call Core (Necessary for Database Interaction
global $plusTG;
// If Search
if($search)
{
$searchString = ' AND (name LIKE "%'.$search.'%")';
}
else
{
$searchString = '';
}
// Validate Query
$search = $plusTG->validateQuery($search);
$type = $plusTG->validateQuery($type);
$genre = $plusTG->validateQuery($genre);
// Check Numeric
if((!is_numeric($genre)))
{
return false;
}
else
{
if(!is_numeric($type))
{
if($type != 0)
{
$typeSelect = '';
$split = explode(',',$type);
foreach($split as $oneType)
{
if($typeSelect == '')
{
$typeSelect .= 'type = '.$oneType.' ';
}
else
{
$typeSelect .= 'OR type = '.$oneType.' ';
}
}
}
}
else
{
$typeSelect = 'type = ' . $type . ' ';
}
//echo $typeSelect;
$limit = ($page - 1) * 20;
if(($type != 0) && ($genre != 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1 AND genre = '.$genre.' AND ('.$typeSelect.')'.$searchString.' ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1 AND genre = '.$genre.' AND ('.$typeSelect.')'.$searchString);
}
elseif(($type == 0) && ($genre != 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1 AND genre = '.$genre.$searchString.' ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1 AND genre = '.$genre.$searchString);
}
elseif(($type != 0) && ($genre == 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1 AND ('.$typeSelect.')'.$searchString.'ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1 AND ('.$typeSelect.')'.$searchString);
}
elseif(($type == 0) && ($genre == 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1'.$searchString.' ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1'.$searchString);
}
$this->buildInfo($items->num_rows, $total->fetch_assoc());
while($singleItem = $items->fetch_assoc())
{
$this->addItem($singleItem);
}
}
return true;
}
The build info call & add item call are adding the items to the DOMXML.
This is my javascript (domain and filename filtered):
function itemRequest(type,genre,page, search)
{
if(ajaxReady != 0)
{
ajaxReady = 0;
$('#item_container').text('');
var searchUrl = '';
var searchLink;
var ajaxURL;
if(search != 0)
{
searchUrl = '&search=' + search;
searchLink = search;
ajaxURL = "/////file.php";
}
else
{
searchLink = 0;
ajaxURL = "////file.php";
}
$.ajax({
type: "GET",
url: ajaxURL,
data: "spec=1&type="+type+"&genre="+genre+"&page="+page+searchUrl,
success: function(itemListing){
$(itemListing).find('info').each(function()
{
var total = $(this).find('total').text();
updatePaging(total, page, type, genre, searchLink);
});
var items = $(itemListing).find('items');
$(items).find('item').each(function()
{
var itemId = $(this).find('id').text();
var itemType = $(this).find('type').text();
var itemGenre = $(this).find('genre').text();
var itemTmId = $(this).find('tm').text();
var itemName = $(this).find('name').text();
buildItem(itemId, itemType, itemGenre, itemTmId, itemName);
});
$('.item_one img[title]').tooltip();
},
complete: function(){
ajaxReady = 1;
}
});
}
Build item calls this:
function buildItem(itemId, itemType, itemGenre, itemTmId, itemName)
{
// Pick up Misc. Data
var typeName = nameOfType(itemType);
// Create Core Object
var anItem = $('<div/>', {
'class':'item_one'
});
// Create Item Image
$('<img/>', {
'src':'///'+typeName+'_'+itemTmId+'_abc.png',
'alt':itemName,
'title':itemName,
click:function(){
eval(typeName + 'Type = ' + itemTmId);
$('.equipped_item[name='+typeName+']').attr('src','//'+typeName+'_'+itemTmId+'_abc.png');
$('.equipped_item[name='+typeName+']').attr('alt',itemName);
$('.equipped_item[name='+typeName+']').attr('title',itemName);
$('.equipped_item[title]').tooltip();
recentEquipped(typeName, itemTmId, itemName);
updateSelfy();
}
}).appendTo(anItem);
// Favs
var arrayHack = false;
$(favEquips).each(function(){
if(arrayHack == false)
{
if(in_array(itemTmId, this))
{
arrayHack = true;
}
}
});
var itemFaved = '';
if(arrayHack == true)
{
itemFaved = 'activated';
}
$('<div/>',{
'class':'fav',
'id':itemFaved,
click:function(){
if($(this).attr('id') != 'activated')
{
$(this).attr('id','activated');
}
else
{
$(this).removeAttr('id');
}
itemFav(itemTmId, typeName, itemName);
}
}).appendTo(anItem);
$(anItem).appendTo('#item_container');
}
If anyone could help me improve this code, it'd be very much appreciated.
add an index to your table for cat column
figure out what the bottleneck is, if it is your XML then try json,
if it is your network, try enabling gzip compression
I agree with Zepplock, it is important to find out where the bottleneck is - if not, you're only guessing. Zepplock's list is good but I would also add caching:
Find out where the bottleneck is.
Use indexes in your db table.
Cache your query results
Find the Bottleneck.
There are number opinions and ways to do this... Basically when your site is under load, get the time it takes to complete each step in the process: The DB queries, the server-side processes, the client side processes.
Use Indexes.
If your DB is slow chances are you can get a lot of improvement by optimizing your queries. A table index may be in order... Use 'EXPLAIN' to help identify where indexes should be placed to optimize your queries:
EXPLAIN SELECT * FROM dream_items WHERE active = 1 AND (name LIKE "%foo%") ORDER BY name LIMIT 0,20;
(I bet an index on active and name would do the trick)
ALTER TABLE `dream_items` ADD INDEX `active_name` (`active` , `name`);
Also try to avoid using the wildcard '*'. Instead only ask for the columns you need. Something like:
SELECT `id`, `type`, `genre`, `tm`, `name` FROM `dream_items` WHERE...
Cache Your Results.
If the records in the DB have not changed then there is no reason to try an re-query the results. Use some sort of caching to reduce the load on your DB (memcached, flat file, etc..). Depending on the database class / utilities you're using it may already be capable of caching results.

Categories