Flash Database Operation Failed - php

I have a problem with my Flash (.fla) project. I've connected my flash with database with php script. I used ActionScript 2.0.
The problem is data can show at compile program on AdobeFlash CS6 (CTRL+Enter) but data cant show in datagrid when I open the .swf.
It's my php script
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("modul");
$qr = mysql_query("SELECT * from nilaisiswa");
if (!qr || mysql_num_rows($qr)==0) {
$r_string = '&errorcode=3&msg='.mysql_error().'&';
} else {
$r_string = '&errorcode=0&n='.mysql_num_rows ($qr);
$i = 0;
while ($row = mysql_fetch_assoc ($qr)) {
while (list ($key, $val) = each ($row)) {
$r_string .= '&' . $key . $i . '=' . stripslashes($val);
}
$i++;
}
$r_string .='&';
}
echo $r_string;
?>
And here it's my ActionScript 2.0
var select_lv:LoadVars = new LoadVars();
var insert_lv:LoadVars = new LoadVars();
var delete_lv:LoadVars = new LoadVars();
var today:Date = new Date();
var deleteIndex:Number;
var errorMsgs:Array = [
"",
"Couldn't connect to server",
"Couldn't connect to database",
"Error running query",
"First four entries may not be deleted"];
var filepath:String;
var scoreInfo:Array = [];
var headerListener:Object = {};
headerListener.headerRelease = function(event:Object) {
switch (event.columnIndex) {
case 0:
if (scores_dg.getColumnAt(0).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE);
}
scores_dg.getColumnAt(0).sortedUp = !scores_dg.getColumnAt(0).sortedUp;
break;
case 1:
if (scores_dg.getColumnAt(1).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC);
}
scores_dg.getColumnAt(1).sortedUp = !scores_dg.getColumnAt(1).sortedUp;
break;
}
}
function zerofill(n:Number):String {
if (n<10) return '0' + n.toString();
else return n.toString();
}
filepath = "http://localhost/tesis/";
nickname_ti.maxChars = 50;
date_ti.maxChars = 10;
score_ti.text = 0;
date_ti.text = today.getDate() + '-' + zerofill(today.getMonth()+1) + '-' + zerofill(today.getFullYear());
select_lv.onLoad = function(ok:Boolean) {
if (ok) {
if (this.errorcode=="0") {
for (var i:Number=0; i < this.n; i++) {
scoreInfo.push(
{record:this["id"+i],
nickname:this["nickname"+i],
score:Number(this["score"+i]),
dateposted:this["dateposted"+i]
});
}
scores_dg.columnNames = ["nickname", "score", "dateposted"];
scores_dg.getColumnAt(0).width = 130;
scores_dg.getColumnAt(0).sortOnHeaderRelease = false;
scores_dg.getColumnAt(0).sortedUp = false;
scores_dg.getColumnAt(0).headerText = "Nickname";
scores_dg.getColumnAt(1).width = 130;
scores_dg.getColumnAt(1).sortOnHeaderRelease = false;
scores_dg.getColumnAt(1).sortedUp = false;
scores_dg.getColumnAt(1).headerText = "Score";
scores_dg.getColumnAt(2).width = 130;
scores_dg.getColumnAt(2).headerText = "Date Posted";
scores_dg.dataProvider = scoreInfo;
scores_dg.addEventListener("headerRelease", headerListener);
msg_ta.text = "Enter data and click Add to add a score.";
} else {
msg_ta.text = errorMsgs[Number(this.errorcode)];
if (this.errorcode == "3") msg_ta.text += ": " + this.msg;
}
} else {
msg_ta.text = "Flash-database select operation failed";
}
}
msg_ta.text = "Getting high scores from database...";
select_lv.sendAndLoad(filepath + "getscores.php", select_lv, "GET");

Related

Ajax search from mysql databse unicode failure

I hope moderators doesn't mark this question as duplicated cause i research for this problem almost 1week and can't figure out what is wrong.
I have this code, for searching data from MySQL database tables, atm it doesn't read Unicode chars. My guess is $_GET function string to read Unicode chars, because of that, I sated MySQL table charset to utf-8 and columns collation are utf8_general_ci and also I added this two lines into php code:
header('Content-Type: text/html; charset=utf-8');
mysqli_set_charset($connect,'utf8');
but still the result of Unicode chars are 0. If I type "a" in input, it shows the all words which starts by "a" or "ä,å á..." but, if I type some Unicode char for example "ä" it says "no result founded".
Code is also online atm here is the link http://dic.munjutut.fi/php/
Also I have added utf-8 meta to HTML file. I hope someone tell me what is wrong. The code itself is:
header('Content-Type: text/html; charset=utf-8');
mysqli_set_charset($connect,'utf8');
if(isset($_GET['p'])) {
$page_number = $_GET['p'];
$arraySearch = $_GET['terms'];
$show_count = $_GET['count'];
settype($page_number, 'integer');
}
$nospaces = substr($_GET['terms'],1,4);
$offset = ($page_number - 1) * $records_number;
// check for an empty string and display a message.
if ($_GET['terms'] == "") {
echo '<div id="counter">Type "äää" or "ääää"!</div>';
// minim 3 characters condition
} else if(strlen($_GET['terms']) < $limitchar) {
echo '<div id="counter">'. $limitchar .' characters minimum</div>';
} else {
// explode search words into an array
$arraySearch = explode(" ", $_GET['terms']);
// table fields to search
$arrayFields = array(0 => $first_field, 1 => $second_field);
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM $table_name WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.") LIMIT $offset, $records_number;";
$search = mysqli_query($connect, $query);
// get number of search results
$arrayFields = array(0 => $first_field);
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM $table_name WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.")";
$count_results = mysqli_query($connect, $query) or die(mysqli_error($connect));
$numrows = mysqli_num_rows($count_results);
// no results
if($numrows == 0) {
echo '<div id="counter">No results found</div>';
// show results
} else {
echo '<div id="results">
<div id="results_top"><p><b>'. $_GET['terms'] .'</b> - '. $numrows .' results found</p></div>
';
Ajax codes in 2 file:
search_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (search_id != '') {
document.getElementById(search_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();
function getScriptPage(div_id,terms_id,get_count,get_p) {
search_id = div_id;
zearch = document.getElementById(terms_id).value;
http.open("GET", "search.php?terms=" + escape(zearch)+"&count="+get_count+"&page="+get_p, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
and
function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
// show_results will be filled with new page
document.getElementById("show_results").innerHTML = xmlHttp.responseText;
document.getElementById("show_results").scrollIntoView();
}
}
function htmlData(url, terms, pag)
{
if (url.length==0)
{
document.getElementById("show_results").innerHTML = "";
return;
}
xmlHttp = GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
url=url+"?"+terms+"&"+pag;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET",url,true) ;
xmlHttp.send(null);
}
#CBroe fixed this for me! Big thanks for him! Problem was with AJAX and encoding. I used escape function instead encodeURIComponent. Here the fixed code:
Old one:
http.open("GET", "search.php?terms=" + escape(zearch)+"&count="+get_count+"&page="+get_p, true);
Fixed:
http.open("GET", "search.php?terms=" + encodeURIComponent(zearch)+"&count="+get_count+"&page="+get_p, true);

PHP HTTP 500 Error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I decompined this script of ioncube. The encripted script runs totally fine. But when I run the decrypt script the page gives me 500 Http error. The decrypt script is this:
<?php
/
$_X=base64_decode($_X);$_X=strtr($_X,'123456aouie','aouie123456');$_R=ereg_replace('__FILE__',"'".$_F."'",$_X);eval($_R);$_R=0;$_X=0;
?>
<?php
/
?><?php
#author: A S M Abdur Rab [shibly], shibly#divine-it.net
#abstract: Class for authentication.
#abstract: Helpful methods to make the session/cookies handling, login, logout,
timedout, admin/user authentication, redirection and other authentication
related process safe.
PHP versions 4 and 5
#name: Authentication Class.
#category: Class.
#uses:
#version:
#package: divin_framework
#subpackage: divin_framework.libs
/
class AuthComponent extends Component
{
set allowable IP addresses here/
var $allowedIpAddresses = array('127.0.0.1','192.210.144.165',
'::1');
var $productId = '1001';
var $model = '';
var $condition = '';
var $secretSalt = 'dddonteeeventtthinkaaaboutiiit';
var $msgLogout = 'Logout Successfully.';
var $msgLoggedIn = 'Already logged in.';
var $msgNotLoggedIn = 'You are not logged in.';
var $msgInvalidUser = 'Username and/or Password invalid.';
var $msgTooManyAttempts = 'You have exceeded maximum login attempt limit.';
var $loginPage = 'Login';
var $afterLogoutPage = 'Login';
var $logoutPage = 'Logout';
var $homePage = 'index';
var $site = 'DivineIT';
var $fields = array('login', 'password');
var $timeOffset = 180;
var $loginRequired = false;
var $loginController = null;
var $_authSession = null;
var $_authModel = null;
var $_sessionName = null;
var $sessionId = null;
function __construct()
{
global $AUTH;
if(isset($AUTH))
{
$this->loginRequired = true;
foreach($AUTH as $key => $value)
$this->{$key} = $value;
}
if(!empty($this->model))
{
$this->_sessionName = $this->site . '.' . $this->model;
$this->_authSession = &App::loadModel('AuthSession');
$this->_authModel = &App::loadModel($this->model);
}
}
function startup(&$controller)
{
$permitted = false;
foreach($this->allowedIpAddresses as $ipAddress)
{
if($_SERVER['SERVER_ADDR']===$ipAddress)
{
$permitted = true;
break;
}
}
if(!$permitted)
{
header('Location: forbidden.php');
return;
}
if(defined('PREFIX'))
$prefix = PREFIX;
else
$prefix = '';
if($this->_authModel === null || $this->_authSession === null)
{
if($this->loginRequired === true)
{
$controller->redirect($this->loginController, $this->loginPage);
}
return;
}
$count = count($this->fields);
if($prefix.$this->loginPage == Router::$action && isset($controller->data[$this->model]) && (count($controller->data[$this->model]) == $count))
{
max login attempts#start/
$tryInfo = null;
$tryInfo = $this->Session->get('login_attempts');
if(!is_null($tryInfo))
{
$firstImpression = $tryInfo['first_impression'];
$loginAttempts = $tryInfo['login_attempts'];
$lastImpression = strtotime($tryInfo['last_impression']);
$currentTime = strtotime(currentTime());
if(($currentTime - $lastImpression)>$this->loginLockDuration60)
{
$loginAttempts = 1;
}
if(($loginAttempts>$this->maxLoginAttempts)&&($currentTime - $lastImpression)<$this->loginLockDuration60)
{
$controller->setFlash($this->msgTooManyAttempts);
$controller->redirect($this->loginController, $this->loginPage);
return;
}
else
{
$loginAttempts++;
$tryInfo['login_attempts'] = $loginAttempts;
$tryInfo['last_impression']= currentTime();
$this->Session->set('login_attempts', $tryInfo);
}
}
else
{
$tryInfo['login_attempts'] = 1;
$tryInfo['first_impression'] = currentTime();
$tryInfo['last_impression'] = currentTime();
$this->Session->set('login_attempts', $tryInfo);
}
max login attempts#start/
$this->loggedIn = $this->__login($controller->data[$this->model], $this->condition);
if($this->loggedIn)
{
$requestedPage = $this->Session->get('requested_url');
if(!is_null($requestedPage)&&(count($requestedPage)>0))
{
$requestedController = Inflector::underscore($requestedPage['controller']);
$requestedAction = Inflector::underscore($requestedPage['action']);
$requestedParams = $requestedPage['params'];
$requestedMoreAttrs = $requestedPage['more'];
$requestedScript = $requestedPage['script'];
$this->Session->remove('requested_url');
//$controller->redirect($requestedController, $requestedAction,$requestedParams, $requestedMoreAttrs);
$link = $requestedScript . '?action=' . $requestedController . '-' .
$requestedAction . (!empty($requestedParams) ? ('-'.implode('-', $requestedParams)) : '');
if(!empty($requestedMoreAttrs))
{
foreach($requestedMoreAttrs as $key=>$value)
{
$link .= '&'.$key.'='.$value;
}
}
header('location: ' . $link);
}
else
{
$controller->redirect($this->loginController, $this->homePage);
}
return;
}
else
{
$controller->setFlash($this->msgInvalidUser);
$controller->redirect($this->loginController, $this->loginPage);
}
}
else
{
if(Router::$action != $prefix.$this->loginPage)
{
if(Router::$action === $prefix.$this->logoutPage)
{
$this->__logout();
$controller->setFlash($this->msgLogout);
$controller->redirect($this->loginController, $this->afterLogoutPage);
}
else if($this->__checkValidSession() === false)
{
$requestedPage = $this->Session->get('requested_url');
$requestedPage['controller'] = Router::$controller;
$requestedPage['action'] = Router::$originalAction;
$requestedPage['params'] = Router::$params;
$requestedPage['more'] = Router::$more;
$requestedPage['script'] = Router::$script;
$this->Session->set('requested_url', $requestedPage);
$controller->setFlash($this->msgNotLoggedIn);
$controller->redirect($this->loginController, $this->loginPage);
}
else
{
$this->loggedIn = true;
}
}
}
}
function __login($values, $condition)
{
if(method_exists($this->model, 'authenticate'))
{
$userData = $this->_authModel->authenticate($values, $condition);
}
else
{
foreach($this->fields as $field)
{
if($field === 'password')
{
if($this->encryptPassword)
{
$value = &Database::escape($this->password($values[$field]));
}
else
{
$value = &Database::escape($values[$field]);
}
}
else
{
$value = &Database::escape($values[$field]);
}
$condition .= (empty($condition)?'':' AND ') . '`' . $this->model . '`.' .'`'.$field.'` COLLATE latin1_bin = \''.$value."'";
}
$userData = $this->_authModel->find($condition);
}
if($userData != null)
{
/ TODO: if disable /
// $this->Session->regenerate();
$userSessionId = $this->Session->sessionId();
$this->Session->set( $this->_sessionName, $userSessionId );
$userSessionId = sha1($this->_sessionName . $userSessionId . $this->secretSalt);
$userSessionData = array('AuthSession' =>
array('session_id' => $userSessionId,
'login_time' => currentTime(),
'last_impression' => currentTime(),
'ip' => $_SERVER['REMOTE_ADDR'],
'user_id'=> $userData[$this->model][$this->_authModel->primaryKey],
'model'=> $this->model,
'user_data'=>serialize($userData)
)
);
if($this->_authSession->save($userSessionData, false) === true)
{
$this->userData = &$userData;
$this->sessionId = $userSessionId;
$this->Session->remove('login_attempts');
return true;
}
}
return false;
}
function __logout()
{
Remove from session table.
/
$sessionId = sha1($this->_sessionName . $this->Session->get($this->_sessionName) . $this->secretSalt);
$condition = '`session_id` = \'' . $sessionId . '\' AND `model` = \''.$this->model.'\'';
//$condition.= ' AND `ip`=\'' . $_SERVER['REMOTE_ADDR'] .'\'';
$this->_authSession->delete($condition);
Remove all invalid/expired sessions.
/
$sessionDuration = $this->timeOffset 60;
$inactivityInterval = $this->inactivityInterval 60;
$condition = '(UNIX_TIMESTAMP(\'' . currentTime() . '\') - UNIX_TIMESTAMP(last_impression)) > ' . $inactivityInterval;
$this->_authSession->delete($condition);
$condition = '';
$this->Session->destroySession();
}
function __checkValidSession()
{
$sessionId = sha1($this->_sessionName . $this->Session->get($this->_sessionName) . $this->secretSalt);
// check if session available
$sessionDuration = $this->timeOffset 60;
$inactivityInterval = $this->inactivityInterval 60;
$condition = '(UNIX_TIMESTAMP(\'' . currentTime() . '\') - UNIX_TIMESTAMP(last_impression)) > ' . $inactivityInterval;
$this->_authSession->delete($condition);
$condition = '';
$condition = "session_id = '" . $sessionId . "' AND `model`= '{$this->model}'";
//$condition .= ' AND ip=\'' . $_SERVER['REMOTE_ADDR'] . '\'';
$checkValidSession = $this->_authSession->find($condition);
if(count($checkValidSession) === 1)
{
// check if session expired
$timeOut = strtotime($checkValidSession['AuthSession']['login_time']) + $sessionDuration;
$currentTime = strtotime(currentTime());
if($timeOut > $currentTime)
{
// find logged in user
if(method_exists($this->_authModel, 'checkSession'))
{
$userData = &$this->_authModel->checkSession(unserialize($checkValidSession['AuthSession']['user_data']));
}
else
{
$conditions = $this->model . '.' . $this->_authModel->primaryKey.'=' . $checkValidSession['AuthSession']['user_id'];
$userData = & $this->_authModel->find($conditions);
}
if($userData != null)
{
/ TODO: if disable /
$sessionId = sha1($this->_sessionName . $this->Session->get($this->_sessionName) . $this->secretSalt);
$condition = '`session_id` = \'' . $sessionId . '\' AND `model` = \''.$this->model.'\'';
//$condition.= ' AND `ip`=\'' . $_SERVER['REMOTE_ADDR']. '\'';
$data = array();
$data['AuthSession']['last_impression'] = currentTime();
$this->_authSession->update($data, '', $condition);
$this->userData = & $userData;
return true;
}
}
}
$this->_authSession->delete($condition);
$this->Session->destroySession();
return false;
}
function password($password)
{
return sha1($password);
}
function user($field)
{
if(isset($this->userData[$this->model][$field]))
return $this->userData[$this->model][$field];
return null;
}
}
?>
?>
What's wrong in this script that is giving me 500 error?
There are Multiple Errors in the code. Here is the List!
Syntax Error : MultiLine Comments
Line 8 : Unexpected "/" # it Should be /* or */
Line 20: Unexpected "/" # It should be /* or */
Lines 24-39 : You forgot to start the MultiLine Comment!
Line 43 : Again you forgot to Start single Line Comment!
Line 122 : Again you forgot to start and end Single Line comment!
Line 159 : Don't know if you forgot to start comment or bad code!
Line 261 : Again forgot to start and end the comment!
Line 290 and 297 : Forgot to start and end the comment!
Line 291 and 298 : Syntax error! Looks like you wanted to start comment!
Line 339 : Syntax Error In MultiLine Comment! I am tired of writing again! :v
These are just Comment Errors!
There are multiple Variable Definition errors too! There are other Multiple errors! Check the full code once!

Sorting of html-table with data from sql-query by clicking on field-name

I have an sql-database, where data can be read out by an html-form. The data are shown in an html-table, this works fine! However, I would like to make the table sortable, which means, that by clicking on the respective field-name the data should be sorted according to this field (ascending/descending). I have tried different javaScript-solutions including tablesorter.com that work well in "normal" tables, however, not in this table that is built dynamically with data from a database. Here is my code that creates the table (code without specific link to JavaScript-files):
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql) or die("Invalid query"); //Running the
query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
$row = mysqli_fetch_array($result);
if ($numrows > 0) {
echo "<table id=myTable class=tablesorter>";
echo "<thead><tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr></thead>";
echo "<tbody><tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr></tbody>";
}
echo "</table>";
}
}
mysqli_close($db);
?>
One of the javaScript-files I tried:
(function () {
"use strict";
var tableSort = function (tab) {
var titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[
0].getElementsByTagName("th");
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen == 0) return;
var nspalten = tz[0].cells.length;
var arr = new Array(nzeilen);
var sortiert = -1;
var sorttype = new Array(nspalten);
var sortbuttonStyle = document.createElement
('style'); // Stylesheet für Button im TH
sortbuttonStyle.innerText =
'.sortbutton { width:100%; height:100%; border:
none; background-color: transparent; font: inherit; color: inherit; text-
align: inherit; padding: 0; cursor: pointer; } .sortbutton::-moz-focus-
inner { margin: -1px; border-width: 1px; padding: 0; }';
document.head.appendChild(sortbuttonStyle);
var initTableHead = function (sp) { // Kopfzeile
vorbereiten
var b = document.createElement("button");
b.type = "button";
b.className = "sortbutton";
b.innerHTML = titel[sp].innerHTML;
b.addEventListener("click", function () {
tsort(sp);
}, false);
titel[sp].innerHTML = "";
titel[sp].appendChild(b);
}
var getData = function (ele, s) {
var val = ele.innerHTML;
if (!isNaN(val) && val.search(/[0-9]/) !
= -1) return val;
var n = val.replace(",", ".");
if (!isNaN(n) && n.search(/[0-9]/) !=
-1) return n;
sorttype[s] = "s"; // String
return val;
} // getData
var vglFkt_s = function (a, b) {
var as = a[sortiert],
bs = b[sortiert];
if (as > bs) return 1;
else return -1;
} // vglFkt_s
var vglFkt_n = function (a, b) {
return parseFloat(a[sortiert]) -
parseFloat(b[sortiert]);
} // vglFkt_n
var tsort = function (sp) {
if (sp == sortiert) arr.reverse(); //
Tabelle ist schon nach dieser Spalte sortiert, also nur Reihenfolge
umdrehen
else { // Sortieren
sortiert = sp;
if (sorttype[sp] == "n")
arr.sort(vglFkt_n);
else arr.sort(vglFkt_s);
}
for (var z = 0; z < nzeilen; z++)
tbdy.appendChild(arr[z][nspalten]); // Sortierte Daten zurückschreiben
} // tsort
// Kopfzeile vorbereiten
for (var i = 0; i < titel.length; i++) initTableHead(i);
// Array mit Info, wie Spalte zu sortieren ist,
vorbelegen
for (var s = 0; s < nspalten; s++) sorttype[s] = "n";
// Tabelleninhalt in ein Array kopieren
for (var z = 0; z < nzeilen; z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
arr[z] = new Array(nspalten + 1);
arr[z][nspalten] = tz[z];
for (var s = 0; s < nspalten; s++) {
var zi = getData(zelle[s], s);
arr[z][s] = zi;
// zelle[s].innerHTML
+= "<br>"+zi+"<br>"+sorttype[s]; // zum Debuggen
}
}
} // tableSort
var initTableSort = function () {
var sort_Table = document.querySelectorAll
("table.sortierbar");
for (var i = 0; i < sort_Table.length; i++) new
tableSort(sort_Table[i]);
} // initTable
if (window.addEventListener) window.addEventListener("DOMContentLoaded",
initTableSort, false); // nicht im IE8
})();
Another of the javaScript-files I tried:
( function() {
"use strict";
var JB_sortbutStyle = document.createElement('style'); // Stylesheet
für Button im TH
JB_sortbutStyle.innerText = 'button.sortbut { width:100%; height:100%;
border: none; background-color: transparent; font: inherit; color:
inherit; text-align: inherit; padding: 0; cursor: pointer; }
button.sortbut::-moz-focus-inner { margin: -1px; border-width: 1px;
padding: 0; }';
document.head.appendChild(JB_sortbutStyle);
var JB_Table = function(tab) {
var up = String.fromCharCode(9650);
var down = String.fromCharCode(9660);
// var up = String.fromCharCode(8593);
// var down = String.fromCharCode(8595);
// var up = String.fromCharCode(11014);
// var down = String.fromCharCode(11015);
var no = String.fromCharCode(160,160,160,160); // Idee: 9674 ???
var dieses = this;
var defsort = 0;
var startsort_u = -1,startsort_d = -1;
var first = true;
var ssort;
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen==0) return;
var nspalten = tz[0].cells.length;
var Titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[0].getElementsByTagName("th");
var Arr = new Array(nzeilen);
var ct = 0;
var sdir = new Array(nspalten);
var stype = new Array(nspalten);
var sortable = new Array(nspalten);
for(var i=0;i<nspalten;i++) {
stype[i] = "n";
sdir[i] = "u";
sortable[i] = false;
}
var initTableHead = function(t,nr) {
var b = document.createElement("button");
b.type = "button";
b.className = "sortbut"
b.innerHTML = t.innerHTML;
t.innerHTML = "";
if(window.addEventListener) b.addEventListener
("click",function() { dieses.sort(nr); },false);
b.title = 'Die Tabelle nach "'+b.textContent+'"
sortieren.';
t.appendChild(b);
sortsymbol.init(t,no);
if(t.className.indexOf("vorsortiert-")>-1) {
sortsymbol.set(t,down);
ssort = nr;
}
else if(t.className.indexOf("vorsortiert")>-1) {
sortsymbol.set(t,up);
ssort = nr;
}
if(t.className.indexOf("sortiere-")>-1) startsort_d=nr;
else if(t.className.indexOf("sortiere")>-1)
startsort_u=nr;
sortable[nr] = true;
} // initTableHead
var sortsymbol = {
init: function(t,s) {
var tt = t.querySelector("button");
var sp = tt.getElementsByTagName("span");
for(var i=0;i<sp.length;i++) {
if(!sp[i].hasChildNodes()) {
t.sym = sp[i].appendChild
(document.createTextNode(s));
break;
}
}
if(typeof(t.sym)=="undefined") t.sym =
tt.appendChild(document.createTextNode(s));
},
set: function(t,s) {
t.sym.data = s;
},
get: function(t) {
return t.sym.data;
}
} // sortsymbol
var VglFkt_s = function(a,b) {
var as = a[ssort], bs = b[ssort];
var ret=(as>bs)?1:(as<bs)?-1:0;
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { as = a[defsort]; bs
= b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort])
}
return ret;
} // VglFkt_s
var VglFkt_n = function(a,b) {
var ret = parseFloat(a[ssort])-parseFloat(b[ssort]);
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { var as = a
[defsort],bs = b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort]);
}
return ret;
} // VglFkt_n
var convert = function(val,s) {
var dmy;
var trmdat = function() {
if(dmy[0]<10) dmy[0] = "0" + dmy[0];
if(dmy[1]<10) dmy[1] = "0" + dmy[1];
if(dmy[2]<10) dmy[2] = "200" + dmy[2];
else if(dmy[2]<20) dmy[2] = "20" + dmy[2];
else if(dmy[2]<99) dmy[2] = "19" + dmy[2];
else if(dmy[2]>9999) dmy[2] = "9999";
}
if(val.length==0) val = "0";
if(!isNaN(val) && val.search(/[0-9]/)!=-1) return val;
var n = val.replace(",",".");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
n = n.replace(/\s| | |\u00A0/g,"");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
dmy[5] = val.substring(dp+4,dp+6);
for(var i=0;i<6;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<6;i++) if(dmy[i]<10) dmy[i] = "0"
+ dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]+dmy[5]).replace(/ /g,"");
}
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
for(var i=0;i<5;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<5;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<3;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]+"."+dmy[2]).replace
(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<2;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<2;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+/)) {
dmy = val.split(".");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
return (""+dmy[2]+dmy[1]+dmy[0]).replace
(/ /g,"");
}
stype[s] = "s";
// return val.toLowerCase().replace(/
\u00e4/g,"ae").replace(/\u00f6/g,"oe").replace(/\u00fc/g,"ue").replace(/
\u00df/g,"ss");
return val.toLowerCase().replace(/\u00e4/g,"a ").replace
(/\u00f6/g,"o ").replace(/\u00fc/g,"u ").replace(/\u00df/g,"ss");
} // convert
this.sort = function(sp) {
if(sp<0 || sp>=nspalten) return;
if(!sortable[sp]) return;
if (first) {
for(var z=0;z<nzeilen;z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
Arr[z] = new Array(nspalten+1);
Arr[z][nspalten] = tz[z];
for(var s=0;s<nspalten;s++) {
if (zelle[s].getAttribute("data-
sort_key"))
var zi = convert(zelle
[s].getAttribute("data-sort_key"),s);
else if (zelle[s].getAttribute
("sort_key"))
var zi = convert(zelle
[s].getAttribute("sort_key"),s);
else
var zi = convert(zelle
[s].textContent,s);
Arr[z][s] = zi ;
// zelle[s].innerHTML
+= "<br>"+zi; // zum Debuggen
}
}
first = false;
}
if(sp==ssort) {
Arr.reverse() ;
if ( sortsymbol.get(Titel[ssort])==down )
sortsymbol.set(Titel[ssort],up);
else
sortsymbol.set(Titel[ssort],down);
}
else {
if ( ssort>=0 && ssort<nspalten ) sortsymbol.set
(Titel[ssort],no);
ssort = sp;
if(stype[ssort]=="s") Arr.sort(VglFkt_s);
else Arr.sort(VglFkt_n);
if(sdir[ssort]=="u") {
sortsymbol.set(Titel[ssort],up);
}
else {
Arr.reverse() ;
sortsymbol.set(Titel[ssort],down);
}
}
for(var z=0;z<nzeilen;z++)
tbdy.appendChild(Arr[z][nspalten]);
if(typeof(JB_aftersort)=="function") JB_aftersort
(tab,tbdy,tz,nzeilen,nspalten,ssort);
} // sort
if(!tab.title.length) tab.title="Ein Klick auf die
Spalten\u00fcberschrift sortiert die Tabelle.";
for(var i=Titel.length-1;i>-1;i--) {
var t=Titel[i];
if(t.className.indexOf("sortier")>-1) {
ct++;
initTableHead(t,i);
defsort = i ;
if(t.className.indexOf("sortierbar-")>-1) sdir
[i] = "d";
}
}
if(ct==0) {
for(var i=0;i<Titel.length;i++)
initTableHead(Titel[i],i);
defsort = 0;
}
if(startsort_u>=0) this.sort(startsort_u);
if(startsort_d>=0) { this.sort(startsort_d); this.sort
(startsort_d); }
if(typeof(JB_aftersortinit)=="function") JB_aftersortinit
(tab,tbdy,tz,nzeilen,nspalten,-1);
} // JB_Table
var JB_initTableSort = function() {
if (!document.querySelectorAll) return;
var JB_Tables = [];
var Sort_Table = document.querySelectorAll("table.sortierbar,
table[sortable]");
for(var i=0;i<Sort_Table.length;i++) JB_Tables.push(new JB_Table
(Sort_Table[i]));
var pars = decodeURI(window.location.search.substring(1));
if(pars.length) { // jbts=((0,1),(10,0),(3,3),(2,2)) tnr,snr
pars = pars.replace(/\s/g,"");
pars = pars.match(/jbts=\(?(\(\d+,\d+\),?){1,}\)?/gi);
if(pars) {
pars = pars[0].substr(pars[0].search("=")+1);
pars = pars.replace(/\(\(/g,"(").replace(/\)
\)/g,")").replace(/\)\(/g,")|(").replace(/\),\(/g,")|(");
pars = pars.split("|");
for(var i=0;i<pars.length;i++) {
var p = pars[i].substring(1,pars
[i].length-1).split(",");
if(p[0]>-1&&p[0]<JB_Tables.length)
JB_Tables[p[0]].sort(p[1]);
}
}
}
} // initTableSort
if(window.addEventListener) window.addEventListener
("DOMContentLoaded",JB_initTableSort,false);
})();
I would be more than happy if anybody could help me with this Problem!
I used tablesorter for same purpose. I created table dynamically from database and it worked. First add to table id="myTable". After just call the script by adding code below:
$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
Note: Don't forget to include src="jquery.tablesorter.js" (download it from download link).
Now you should be able to sort your table by all columns by just clicking on table header of column.
EDIT:
Insted of:
echo "<table id=myTable class=tablesorter>";
Put:
echo "<table id='myTable' class='tablesorter'>";
How about sorting the table before displaying?
For example, if your link to the page is:
http://example.com/view/product_table
The code for querying the table is:
function getTable($order = null) {
$statement = "SELECT * FROM product_table";
if ($order) {
// switch case to prevent sql injection
switch ($order) {
case: "price":
$statement .= " ORDER BY product_price";
break;
}
}
// Continue the build sql here
}
Have the sorting button redirect to:
http://example.com/view/product_table?sort=price
Call function by:
getTable($GET[sort]);
To further my answer
I would suggest separating the code responsible for displaying and the code for building data
Name your variable to something more meaningful
Currently your code is very hard to maintain and read.

Auto update icons

What I am currently trying to achieve is an auto icon updater. So far I only have it working for 1 icon, but I have 9. Now I have tried to repeat the same code 9 times, try to get it to work from the same file, ect... but to no success. Each icon has a separate timer which will show a different image. (Same image lower opacity)
I want a something which will check the database for the time and see if the time is up, show image 1 if not show image 2.
This is the code I have so far:
function runme() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
var str = "<?echo$id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo$id;?>";
var strhehess = "&username=<?echo$name;?>";
ajaxRequest.open("GET", "auto.php?&id=" + str + strhehes + strhehess + strhehe, true);
ajaxRequest.send(null);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
if (ajaxRequest.status == 200) {
attempt = 0;
document.getElementById("icon_messaging").innerHTML = ajaxRequest.responseText;
document.getElementById("error_mess").innerHTML = '';
document.getElementById("error_mess").style.display = 'none';
} else {
attempt += 1
document.getElementById("error_mess").style.display = 'block';
document.getElementById("error_mess").innerHTML = '<br><font color="#ff4040" onMouseover="ddrivetip(\'There is an error connecting. The game will continue trying to connect again.\')" onMouseout="hideddrivetip()" style="cursor: pointer;">Error Code: ' + new XMLHttpRequest().status + '<br>Attempts: ' + attempt + '</font>';
}
}
}
setTimeout("runme()", 6000);
}
setTimeout("runme()", 5000);
Here is auto.php:
//AUTO INCLUDE
$userids = $_GET['userid'];
$saturate = "/[^a-z0-9]/i";
$saturatesd = "/[^0-9]/i";
$sessionid = preg_replace($saturate,"",$sessionidbefore);
$userid = preg_replace($saturatesd,"",$userids);
$statustest = mysql_query("SELECT newmail,lastactive FROM login WHERE id = '$userids' LIMIT 1");
$statustesttwo = mysql_fetch_array($statustest);
$mails = $statustesttwo['newmail'];
$last_active_1 = $statustesttwo['lastactive'];
if($mails == '0'){
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/mail-yes.gif' style='border-style: none'></a>";
}else{
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/layout/mail-n.jpg' style='border-style: none'></a>";
}
If I understood your question correctly, this is the updating system for the "new mail" icon, and you need to check and update other stuff too. Since you want separate timers, you could parametrize the runme() function. Your JavaScript could be modified like this:
function runme(icon) {
var iconElementId;
var iconTimer;
switch (icon) {
case "mail":
iconElementId = "icon_messaging";
iconTimer = 6000;
break;
case "news":
iconElementId = "icon_notifications"; // I'm making up names and timeouts here
iconTimer = 3000;
break;
case "something":
iconElementId = "icon_something"; // Still making up
iconTimer = 8000;
break;
/* And so on, covering all your 9 cases */
}
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
var str = "<?echo $id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo $id;?>";
var strhehess = "&username=<?echo $name;?>";
ajaxRequest.open("GET", "auto.php?icon=" + encodeURIComponent(icon) + "&id=" + str + strhehes + strhehess + strhehe, true);
ajaxRequest.send(null);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
if (ajaxRequest.status == 200) {
attempt = 0;
document.getElementById(iconElementId).innerHTML = ajaxRequest.responseText;
document.getElementById("error_mess").innerHTML = '';
document.getElementById("error_mess").style.display = 'none';
} else {
attempt += 1;
document.getElementById("error_mess").style.display = 'block';
document.getElementById("error_mess").innerHTML = '<br><font color="#ff4040" onMouseover="ddrivetip(\'There is an error connecting. The game will continue trying to connect again.\')" onMouseout="hideddrivetip()" style="cursor: pointer;">Error Code: ' + new XMLHttpRequest().status + '<br>Attempts: ' + attempt + '</font>';
}
}
}
setTimeout(function(){runme(icon);}, iconTimer);
}
setTimeout(function(){runme("mail");}, 5000);
setTimeout(function(){runme("news");}, 5000);
setTimeout(function(){runme("something");}, 5000);
/* And so on */
So, now your JavaScript sends a GET request to auto.php with the addition of the icon parameter. The PHP script will have to manage that, too.
//AUTO INCLUDE
$icon = urldecode($_GET['icon']);
$userids = $_GET['userid'];
$saturate = "/[^a-z0-9]/i";
$saturatesd = "/[^0-9]/i";
$sessionid = preg_replace($saturate,"",$sessionidbefore);
$userid = preg_replace($saturatesd,"",$userids);
switch($icon) {
case "mail":
$statustest = mysql_query("SELECT newmail,lastactive FROM login WHERE id = '$userids' LIMIT 1");
$statustesttwo = mysql_fetch_array($statustest);
$mails = $statustesttwo['newmail'];
$last_active_1 = $statustesttwo['lastactive'];
if ($mails == '0') {
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/mail-yes.gif' style='border-style: none'></a>";
} else {
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/layout/mail-n.jpg' style='border-style: none'></a>";
}
break;
case "news":
$statustest = mysql_query("SOME OTHER SQL QUERY");
$statustesttwo = mysql_fetch_array($statustest);
/* check whatever you need to */
if (/* something */) {
echo "the HTML for the icon";
} else {
echo "the HTML for the other icon ";
}
break;
/* And so on, again, covering all your 9 cases */
}
Let me know if this works for you.
function runme(icon) {
var iconElementId;
var iconTimer;
switch (icon) {
case "mail":
iconElementId = "icon_messaging";
iconTimer = 5000;
break;
case "gta":
iconElementId = "gta_icon";
iconTimer = <? echo $icon_secs[0]; ?>;
break;
case "burg":
iconElementId = "c_icon";
iconTimer = 5000;
break;
case "crimes":
iconElementId = "crimes_icon";
iconTimer = <? echo $icon_secs[1]; ?>;
break;
case "chase":
iconElementId = "chase_icon";
iconTimer = <? echo $icon_secs[2]; ?>;
break;
case "robbery":
iconElementId = "robbery_icon";
iconTimer = <? echo $icon_secs[3]; ?>;
break;
case "train":
iconElementId = "train_icon";
iconTimer = <? echo $icon_secs[4]; ?>;
break;
case "goods":
iconElementId = "goods_icon";
iconTimer = <? echo $icon_secs[5]; ?>;
break;
case "df":
iconElementId = "df_icon";
iconTimer = <? echo $icon_secs[6]; ?>;
break;
case "sm":
iconElementId = "sm_icon";
iconTimer = <? echo $icon_secs[7]; ?>;
break;
}
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
var str = "<?echo $id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo $id;?>";
var strhehess = "&username=<?echo $name;?>";
ajaxRequest.open("GET", "auto.php?icon=" + encodeURIComponent(icon) + "&id=" + str + strhehes + strhehess + strhehe, true);
ajaxRequest.send(null);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
if (ajaxRequest.status == 200) {
attempt = 0;
document.getElementById(iconElementId).innerHTML = ajaxRequest.responseText;
document.getElementById("error_mess").innerHTML = '';
document.getElementById("error_mess").style.display = 'none';
} else {
attempt += 1
document.getElementById("error_mess").style.display = 'block';
document.getElementById("error_mess").innerHTML = '<br><font color="#ff4040" onMouseover="ddrivetip(\'There is an error connecting. The game will continue trying to connect again.\')" onMouseout="hideddrivetip()" style="cursor: pointer;">Error Code: ' + new XMLHttpRequest().status + '<br>Attempts: ' + attempt + '</font>';
}
}
}
setTimeout("runme('" + icon + "')", iconTimer);
}
setTimeout("runme('mail')", 5000);
setTimeout("runme('gta')", <? echo $icon_secs[0]; ?>);
setTimeout("runme('burg')", 5000);
setTimeout("runme('crimes')", <? echo $icon_secs[1]; ?>);
setTimeout("runme('chase')", <? echo $icon_secs[2]; ?>);
setTimeout("runme('robbery')", <? echo $icon_secs[3]; ?>);
setTimeout("runme('train')", <? echo $icon_secs[4]; ?>);
setTimeout("runme('goods')", <? echo $icon_secs[5]; ?>);
setTimeout("runme('df')", <? echo $icon_secs[6]; ?>);
setTimeout("runme('sm')", <? echo $icon_secs[7]; ?>);
I don't know what your exact problem is. Do you get an error?
What I quickly see is:
attempt += 1
Change this into
if (typeof attempt == "undefined") attempt = 0;
attempt ++;
So add the semi-colon ; , and first check if the var already exists
( ++ is the same as += 1 )
Is this function runme generated by PHP?
var str = "<?echo$id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo$id;?>";
var strhehess = "&username=<?echo$name;?>";
Because if it is not, there is no way this code will work, because Javascript cannot interpret PHP.
In this case, you should put this as attributes of HTML elements and get'em with DOM.
When generating your HTML with PHP, do:
echo '<output id="data-id">' . $id . '<output>';
echo '<output id="data-user-id">' . $id . '<output>';
echo '<output id="data-user-name">' . $username . '<output>';
You can hide this elements with CSS. So then in your Javascript, you should do:
var str = document.getElementById('data-id').innerHTML;
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=" + document.getElementById('data-user-id').innerHTML;
var strhehess = "&username=" + document.getElementById('data-user-name').innerHTML;
Hope it helps.

Cascading Dropdown Boxes

I have used various script and attempted to modify them to suit my database, but this is what I want to Achieve
MySQL Database, single table "Carlist"
I want to put together a form where the user will select a "Make" from the database, this will then filter the 2nd Dropdown box for "Model" where then the third dropdown box will filter out the different variants of that particular model.
MY Database has the fields Make, Model and Version
Box 1: SELECT DISTINCT Make FROM Carlist SORT BY Make
Box 2: SELECT Distinct Model FROM Carlist WHERE Make=$Make SORT BY Model
Box 3: SELECT DISTINCT Version FROM Carlist WHERE Make=$Make AND Model=$Model SORT BY Version
I would also like to put in a mechanism where the 2nd and third boxes could not be selected until the previous box had been
All the scripts I have come across utilise more than one table in the database, at the moment my database has over 1500 records.
If anyone has any useful links or advice on this that would be great, as mentioned I have tried to modify other peoples scripts without success, but those scripts were designed for multiple tables
Assuming that you're trying to fill an HTML form, use Ajax to get the appropriate drop box values from the database after each selection.
Got a solution, code is as follows:
<?php
/* Written for Khaoskreations 2010-06-13 */
//db connect code
require "config.php"; // Your Database details
$query = "SELECT * FROM Carlist ";
$result = mysql_query($query);
//==============================================================================build arrays from db
$Make = array();
$Model = array();
$Version = array();
if (!$result) echo "Error: ".mysql_error();
else {
$Make_group = "";
$Model_group = "";
$num = mysql_num_rows($result);
for ($i = 0;$i<$num;$i++) {
$r = mysql_fetch_array($result);
if ($r['Make'] != $Make_group) {
$Make[$r['Make']] = $r['Make'];
$Model[$r['Make']][$r['Model']] = $r['Model'];
$Version[$r['Make']][$r['Model']][$r['Version']] = $r['Version'];
$Make_group = $r['Make'];
$Model_group = $r['Make'];
} else if ($r['Model'] != $Model_group) {
$Model[$r['Make']][$r['Model']] = $r['Model'];
$Version[$r['Make']][$r['Model']][$r['Version']] = $r['Version'];
$Model_group = $r['Make'];
} else {
$Version[$r['Make']][$r['Model']][$r['Version']] = $r['Version'];
}
}
}
//==============================================================================create scripts
$script = "\n<script type='text/javascript'>\n";
//build last name array
$script .= "var Make = new Array(";
$list = "";
foreach ($Make as $key => $val) {
$list .= " \"".$val."\",";
//echo $val ."<br />";
}
$list = substr($list, 0, -1);
$list .= " );\n";
$script .= $list;
$list = "";
//build Model array
$script .= "\nvar Model = new Array();";
foreach ($Model as $Maken => $fary) {
$list .= "\nModel[\"".$Maken."\"] = new Array(";
foreach ($fary as $key => $value) {
$list .= " \"". $value . "\",";
}
$list = substr($list, 0, -1);
$list .= " );";
}
$script .= $list;
$list = "";
//build Version array
$list = "\nvar Version = new Array();";
foreach ($Version as $Maken => $fary) {
$list .= "\nVersion[\"".$Maken."\"] = new Array();";
foreach ($fary as $Modeln => $aary) {
$list .= "\nVersion[\"".$Maken."\"][\"".$Modeln."\"] = new Array(";
foreach ($aary as $key => $value) {
$list .= " \"" . $value . "\",";
}
$list = substr($list, 0, -1);
$list .= " );";
}
}
$script .= $list;
//script functions to update tiers
$script .= <<< EOSCRIPT
function resetForm(theForm) {
theForm.Makes.options[0] = new Option("--- Select Make ---", "");
for (var i=0; i<Make.length; i++) {
theForm.Makes.options[i+1] = new Option(Make[i], Make[i]);
}
theForm.Makes.options[0].selected = true;
theForm.Models.options[0] = new Option("--- Select Model ---", "");
theForm.Models.options[0].selected = true;
theForm.Version.options[0] = new Option("--- Select Version ---", "");
theForm.Version.options[0].selected = true;
document.getElementById("selectbox").innerHTML = "";
}
function reloadForm(theForm,Manufacturer,product,specific) {
theForm.Makes.options[0] = new Option("--- Select Version ---", "");
for (var i=0; i<Make.length; i++) {
theForm.Makes.options[i+1] = new Option(Make[i], Make[i]);
if (Manufacturer == Make[i]) theForm.Makes.options[i+1].selected = true;
}
document.getElementById("selectbox").innerHTML = "here";
var fn = Model[Manufacturer];
theForm.Models.options.length = 0;
for (var i=0; i<fn.length; i++) {
theForm.Models.options[i] = new Option(fn[i], fn[i]);
if (product == fn[i]) {
theForm.Models.options[i].selected = true;
}
}
var Versions = Version[Manufacturer][product];
theForm.Version.options.length = 0;
for (var i=0; i<Versions.length; i++) {
theForm.Version.options[i] = new Option(Versions[i], Versions[i]);
if (specific == Versions[i][0]) {
theForm.Version.options[i].selected = true;
}
}
document.getElementById("selectbox").innerHTML = "You selected person #"+specific;
}
function updateproducts(theForm) {
var lname = theForm.Makes.options[theForm.Makes.options.selectedIndex].value;
var fnames = Model[lname];
theForm.Models.options.length = 0;
for (var i=0; i<fnames.length; i++) {
theForm.Models.options[i] = new Option(fnames[i], fnames[i]);
}
var findex = theForm.Models.options[theForm.Models.options.selectedIndex].value;
var Versions = Version[lname][findex];
theForm.Version.options.length = 0;
for (var i=0; i<Versions.length; i++) {
theForm.Version.options[i] = new Option(Versions[i], Versions[i]);
}
theForm.Version.options[0].selected = true;
}
function updateVersion(theForm) {
var lname = theForm.Makes.options[theForm.Makes.options.selectedIndex].value;
var findex = theForm.Models.options[theForm.Models.options.selectedIndex].value;
var Versions = Version[lname][findex];
theForm.Version.options.length = 0;
for (var i=0; i<Versions.length; i++) {
theForm.Version.options[i] = new Option(Versions[i], Versions[i]);
}
theForm.Version.options[0].selected = true;
}
</script>
EOSCRIPT;
$reload_script = "";
if ($_POST['Makes'] != "" && $_POST['Models'] != "") {
$reload_script .= "<script type='text/javascript'> "
."reloadForm(document.vehicleform,'".$_POST['Makes']."','".$_POST['Models']."',".$_POST['Version'].");"
."</script>";
} else {
$reload_script .= "<script type='text/javascript'>"
."resetForm(document.vehicleform);"
."</script>";
}
//============================================================================== build page
$page = <<< EOPAGE
<html>
<head>
{$script}
</head>
<body>
<form method="post" action="test3.php" name='vehicleform'>
<select name='Makes' onchange="updateproducts(this.form)"></select><BR>
<select name="Models" onchange="updateVersion(this.form)"></select><BR>
<select name="Version"></select>
<input type='button' value='Reset' onclick='resetForm(document.vehicleform)'/>
<input type='submit' value='Reload'/>
</form>
<div id='selectbox'></div>
{$reload_script}
</body>
</html>
EOPAGE;
echo $page;
?>

Categories