I have a while loop which contains an array which is referencing another file: legProductionAllRecords.php. This file returns an array Which is then used in the loop. I want to be able to use the $orderArray in my javascript tableObj as shown however it is not working. And shows no results when I have no results in $inProgressArray. I also need to be able to use $inProgressArray outside of this loop.
index.php
$madeAt = 2;
$inProgressQuery ="SELECT * FROM leg_prod_inprogress WHERE madeat=".$madeAt;
$inProgressResult = mysql_query($inProgressQuery);
$orderArray = array();
$inProgressArray = array();
while($inProgressArray = mysql_fetch_array($inProgressResult,MYSQL_ASSOC)) {
$inPogressOrder = "-1";
if ($inProgressArray != false) {
$inPogressOrderNo = $inProgressArray['purchase_no'];
} else {
$inPogressOrderNo = -1;
}
require_once('legProductionAllRecords.php');
$allArray = legProductionAllRecords($madeAt, $inPogressOrderNo);
$orderArray = $allArray['allOrder'];
$inPogressOrder = $allArray['inprocessOrder'];
$toadyFinishedOrder = $allArray['todayFinishedOrder'];
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var tableObj = {
data: <?php echo json_encode($orderArray); ?>,
processingData:<?php
if(!empty($inPogressOrder)&&$inPogressOrder!=''){
echo json_encode($inPogressOrder);
}
else{echo -1;} ?>,
}
</script>
</head>
</html>
legProductionAllRecords.php
<?php
function legProductionAllRecords($madeAt,$inPogressOrderNo){
$dayquery = "SELECT * FROM manufacturedat WHERE ManufacturedAtID=".$madeAt;//$madeAt is either 2 or 1
$dayresult = mysql_query($dayquery);
$dayArray = mysql_fetch_array($dayresult,MYSQL_ASSOC);
$day = $dayArray['LegCompletionNoItems'].' days';
$qry = "SELECT a.PURCHASE_No, a.legstyle, a.legfinish, a.LegQty, a.legheight, ".
"a.addlegstyle, a.addlegfinish, a.AddLegQty, a.ORDER_NUMBER, a.specialinstructionslegs, ".
"b.surname, b.first ".
"FROM purchase AS a LEFT JOIN contact AS b ON a.contact_no=b.CONTACT_NO ".
"WHERE a.legrequired='y' ".
"AND a.completedorders = 'n' ".
"AND a.quote = 'n' ".
"AND a.orderonhold = 'n' ".
"AND a.contact_no <> 326314 ".
"AND a.contact_no <> 324273 ".
"AND a.contact_no <> 313820 ".
"AND a.ORDER_DATE >= '2015-12-31' ".
"AND (a.cancelled IS NULL OR a.cancelled <> 'y') ";
$result = mysql_query($qry);
$orderArray = array();
$returnArray['inprocessOrder'] = null;
$returnArray['todayFinishedOrder'] = null;
while ($temp = mysql_fetch_array($result,MYSQL_ASSOC)){
if(!empty($temp)){
$temp['surname'] = mb_convert_encoding($temp['surname'],"UTF-8");
//$temp['title'] = mb_convert_encoding($temp['title'],"UTF-8");
$temp['first'] = mb_convert_encoding($temp['first'],"UTF-8");
$qcQuery = "SELECT * FROM qc_history WHERE ComponentID=7 AND Purchase_No=".$temp['PURCHASE_No']." ORDER BY QC_Date DESC";
$qcresult = mysql_query($qcQuery);
$temp2 = mysql_fetch_array($qcresult,MYSQL_ASSOC);
if($temp2['QC_StatusID']== 20 && $temp2['MadeAt']==$madeAt ){//$temp2['QC_StatusID']== 20 &&
//=====================Change the date format to week:day===============================//
$temp2['formatedBCWExpected'] = date('d/m/Y',strtotime($day,strtotime($temp2['BCWExpected'])));
$tep_time = date_sub(date_create($temp2['BCWExpected']),date_interval_create_from_date_string($day));
$time = explode(':',date_format($tep_time,'W:w'));
$week = (int)$time[0];
$weekday = (int)$time[1];
if($weekday == 0){
$weekday = 5;
}
if($weekday == 6){
$weekday = 5;
}
$temp2['WDdate'] = $week.':'.$weekday;
//=======================End of Change the date format to week:day===============================//
$temp['qc_history'] = $temp2;
$temp['cname'] = $temp['first'].' '.$temp['surname'];
if($temp['PURCHASE_No'] == $inPogressOrderNo){
$returnArray['inprocessOrder'] = $temp;
}
else{
array_push($orderArray, $temp);
}
}
}
}
$returnArray['allOrder'] = $orderArray;
return $returnArray;
}
?>
I have tried the following:
I have used this answer to understand how to reference and update an array outside of a while loop
I have tried including a check for whether $inProgressArray is empty in the while loop like this.
while($inProgressArray = mysql_fetch_array($inProgressResult,MYSQL_ASSOC)||empty($inProgressArray))
however, there is an item in leg_prod_inprogress and it's not shown in the $inProgressArray outside the loop.
Editted 16/11/17 16:13 GMT: Added the details of legProductionAllRecords.php
Editted 2 17/11/17 08:43 GMT: Added the return statement of the return array of the function
Related
My question is: Is there any other method to select the values I need from all the tasks that belongs to same project and sum them? Other method that I tried in the down description?
Description:
I have an app where I can create a Project and, inside the Project, I can create Tasks. For every Task, I can add a percent and calculate a price (example picture 1).
Then I have a report page where I want to calculate all the prices from all of the Tasks of same project (example picture 2).
My problem is when I want to select all the prices from all the tasks that belongs to same projects and sum them in the table "price" of report page.
For the moment I tried a method with the code I put down, and it's not working as I need, because it take the correct value from the first task of the project but dont take corect value from the ohther tasks from the same project
picture 1
picture 2 (but here the problem is that just the first array is corrent the other are not)
code I use ( I commented in the code with "the code that doesnt work" the part that make the sum) :
<?php
defined('BASEPATH') or exit('No direct script access allowed');
$hasPermissionEdit = has_permission('tasks', '', 'edit');
$hasPermissionDelete = has_permission('tasks', '', 'delete');
$tasksPriorities = get_tasks_priorities();
$aColumns = [
db_prefix() . 'tasks.id as id',
db_prefix() . 'tasks.name as task_name',
'count(tbltasks.id) as totaltasks',
//'(SELECT GROUP_CONCAT(name SEPARATOR ",") FROM ' . db_prefix() . 'tasks) as itemlist',
];
$sIndexColumn = 'id';
$sTable = db_prefix() . 'tasks';
$where = [];
$join = [];
$sGroupBy = ' group by '.db_prefix() . 'tasks.rel_id';
// =============== Filter =================
if (isset($ts_filter_data['period-from']) && $ts_filter_data['period-from'] != '' && isset($ts_filter_data['period-to']) && $ts_filter_data['period-to'] != '') {
$ts_filter_from = to_sql_date($ts_filter_data['period-from']);
$ts_filter_from = date('Y-m-d', strtotime($ts_filter_from));
$ts_filter_to = to_sql_date($ts_filter_data['period-to']);
$ts_filter_to = date('Y-m-d', strtotime($ts_filter_to));
}
if (isset($ts_filter_data['this_month']) && $ts_filter_data['this_month'] != '') {
$ts_filter_from = date('Y-m-01');
$ts_filter_to = date('Y-m-t 23:59:59');
}
if (isset($ts_filter_data['last_month']) && $ts_filter_data['last_month'] != '') {
$ts_filter_from = date('Y-m-01', strtotime('-1 MONTH'));;
$ts_filter_to = date('Y-m-t 23:59:59', strtotime('-1 MONTH'));
}
if (isset($ts_filter_data['this_week']) && $ts_filter_data['this_week'] != '') {
$ts_filter_from = date('Y-m-d', strtotime('monday this week'));
$ts_filter_to = date('Y-m-d 23:59:59', strtotime('sunday this week'));
}
if (isset($ts_filter_data['last_week']) && $ts_filter_data['last_week'] != '') {
$ts_filter_from = date('Y-m-d', strtotime('monday last week'));
$ts_filter_to = date('Y-m-d 23:59:59', strtotime('sunday last week'));
}
if($ts_filter_from){
array_push($where, 'AND '.db_prefix().'tasks.startdate >="'.$ts_filter_from.'"');
}
if($ts_filter_to){
array_push($where, 'AND '.db_prefix().'tasks.startdate <="'.$ts_filter_to.'"');
}
// =============== Filter =================
array_push($where, 'AND '.db_prefix().'tasks.rel_type="project"');
// Script By Dev Websyms
$aColumns = hooks()->apply_filters('tasks_table_sql_columns', $aColumns);
// Fix for big queries. Some hosting have max_join_limit
if (count($custom_fields) > 4) {
#$this->ci->db->query('SET SQL_BIG_SELECTS=1');
}
$result = data_tables_init(
$aColumns,
$sIndexColumn,
$sTable,
$join,
$where,
[
'tbltasks.rel_type',
'tbltasks.rel_id',
'tbltasks.task_item_percentage',
'tbltasks.task_duration',
tasks_rel_name_select_query() . ' as rel_name',
get_sql_select_task_assignees_ids() . ' as assignees_ids',
'(SELECT staffid FROM ' . db_prefix() . 'task_assigned WHERE taskid=' . db_prefix() . 'tasks.id AND staffid=' . get_staff_user_id() . ') as is_assigned',
],
$sGroupBy
);
$output = $result['output'];
$rResult = $result['rResult'];
$loop = 1;
foreach ($rResult as $aRow) {
$row = [];
$projectTaskIds = get_assign_project_task($aRow['rel_id']);
$assignees_ids = $aRow['assignees_ids'];
$assignees_id = explode(',', $assignees_ids);
$calA = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
if($projectTaskIds && count($projectTaskIds)){
$realTime = 0;
$estimateCost = 0;
$itemName = '';
$realCost = 0;
$realCostArr = array();
$totalCalEArr = array();
foreach ($projectTaskIds as $key => $projectTaskId) {
// echo $projectTaskId['id'];
// echo "<br>";
$calB = 0;
$calC = 0;
$itemtotal = 0;
$items = get_items_by_type('task', $projectTaskId['id']);
if($items && count($items) > 0){
$itemNo = 1;
foreach ($items as $key => $item) {
$itemtotal += ($item["rate"]*$item["qty"]);
$itemName .= '<div>'.$itemNo.'.'.$item["description"].' <b>('.round($item["qty"]).')</b>'.'</div>';
$itemNo++;
}
}
// =============== the code that doesn't work ============
$calF = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
$calG = get_task_custom_billable_amount($aRow['id']);
$calE = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
if(isset($aRow['task_item_percentage'])){
$calE = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))
*($aRow['task_item_percentage']/100)))
+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
}
$totalCalEArr[] = $calE;
if($totalCalEArr && count($totalCalEArr) > 0){
$totalsCalEaMount = 0;
foreach ($totalCalEArr as $key => $totalvalue) {
$totalsCalEaMount += $totalvalue;
}
}
// =============== the code that doesnt work ============
$realTime += get_calc_task_real_logged_time($projectTaskId['id']);
$calB = get_task_custom_billable_amount($projectTaskId['id']);
if($aRow['task_item_percentage']){
$calC = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
} else {
$calC = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$estimateCost += round($itemtotal+($calA * $aRow['task_duration'] / 60));
$realCost = round($itemtotal+$calB);
// if($calC = 0){ $realCost = round($itemtotal+$calB);} else { $realCost = round($itemtotal+$calB+$calC);
// }
$realCostArr[] = $realCost;
}
if($realCostArr && count($realCostArr) > 0){
$realCostAmount = 0;
foreach ($realCostArr as $key => $reslcostvalue) {
$realCostAmount += $reslcostvalue;
}
}
}
$outputName = '';
$relName = '';
$row[] = $loop;
if ($aRow['rel_name']) {
$relName = task_rel_name($aRow['rel_name'], $aRow['rel_id'], $aRow['rel_type']);
$link = task_rel_link($aRow['rel_id'], $aRow['rel_type']);
$relName = '<span class="hide"> - </span><a class="text-muted task-table-related" data-toggle="tooltip" title="' . _l('task_related_to') . '" href="' . $link . '">' . $relName . '</a>';
}
$row[] = $relName;
$row[] = count($projectTaskIds);
$row[] = $itemName;
$row[] = $aRow['task_duration']*count($projectTaskIds);
$row[] = round($realTime/60);
$row[] = round($estimateCost);
$row[] = round($realCostAmount);
$row[] = '';
$row[] = $totalCalEArr; // display as array or
//$row[] = $totalsCalEaMount; //to display as a sum
$output['aaData'][] = $row;
$loop++;
}
And if you need more details you can find a guide how to use it: http://amco.ro/pdf/Error%20presentation.pdf
I am attempting to build a basic higher or lower game in javascript and insert the results into a table in mysql. After that I am attempting to display the top ten results. Currently I have a rough outline of the game that functions with but am stuck on how to pass the three java script variables to php to insert. I looked up a method of doing this in Ajax an attempted to implement but have not had success yet.
<!DOCTYPE html>
<html>
<?php
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
print $username;
}
?>
<body onload="random()">
<p>Welcome to the higher or lower game</p>
<p>Please enter a guess betweeen 1 and 100</p>
<form id="userGuess">
<input id="ui" type="text" name="UserInput" value="">
</form>
<br>
<br><br>
higher or lower
<br><br>
<p id="demo"></p>
<p id="status"></p>
<p id="rand"></p>
<p id="nan"></p>
<button onclick="comparison()">Submit</button>
<button onclick="reset()">Reset</button>
<script>
var numGuess = 0;
var userIn;
var randNum = 0;
var status;
var method;
//var nan;
function comparison(){
//isnan and parseint
userIn = document.getElementById("ui").value;
//suserIn = parseint(userIn);
//if(isnan(parseint(userIn)){
// nan = "true"
//}
//else{
// nan = "false"
//}
if(userIn == randNum){
//User wins
status = "Correct"
method = "submitScore";
getData({method:"submitScore", score:numGuess, username:username});
window.location = 'http://icarus.cs.weber.edu/~ka14804/3750/A1/results.php'
}
else if(userIn < randNum){
//output higher
status = "Higher"
numGuess++;
}
else if(userIn > randNum){
//output lower
status = "Lower"
numGuess++;
}
document.getElementById("status").innerHTML = status;
document.getElementById("demo").innerHTML = userIn;
document.getElementById("rand").innerHTML = randNum;
document.getElementById("nan").innerHTML = nan;
document.getElementById("nan").innerHTML = numGuess
;
//compare random number to user input. Output higher, lower or match.
}
function reset(){
random();
numGuess = 0;
}
function random() {
randNum = Math.floor((Math.random() * 100) + 1);
}
function getData(obj,callback){
$.ajax({
url: 'resulta.php',
type: 'GET',
dataType: "json",
data: obj
}).done(function(data) {
if(callback != null)
callback(data);
});
}
</script>
</body>
</html>
results.php
<?php
class Results {
public $data;
public $success = true;
public $errorMessage;
}
$func = $_GET["method"];
$obj = new Results();
switch ($func) {
case "getHighScores":
$conn = new mysqli('localhost','','','');
if (!$conn->connect_errno) {
$high = "SELECT * FROM HighScores ORDER BY Score LIMIT 10";
$scores = $conn->query($high);
$arr = array();
while ($row = $scores->fetch_assoc()){
$arr[] = $row;
}
$obj->data = $arr;
echo json_encode($obj);
}
break;
case "submitScore":
$userName = $_GET["username"];
$score = $_GET["score"];
$conn = new mysqli('localhost','','','');
if (!$conn->connect_errno) {
$query = "INSERT INTO HIGHSCORES VALUES('" . $userName . "', '" . $score . "')";
$conn->query($query);
}
break;
default:
echo "Invalid method";
break;
}
?>
I have a form created using HTML and CSS, this form is not for submitting any data in fact it's only for printing purposes.
This form has an input field at top left corner to put a unique 6 digit number to uniquely identify each form.
On the homepage, there is a button link to that form page and I want to increment that serial no which is by default 000000 every time a link button to this form page is clicked.
index.html:
form-1.html:
<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
You have two solution:
Using cookie
Using browser-session
Note: Please comment another solution, while using one solution
main-page.html
<html>
<head>
<title>Main Page</title>
</head>
<body>
Print
</body>
</html>
form-1.html
<html>
<head>
<title>Form Printing</title>
</head>
<body onload="loadNextSeqToForm()">
<form>
<input id="serial" class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
</form>
</body>
<script>
/*
//Solution 1: Using Cookies
function getNextSeq() {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);//Trim the empty space if exists
}
if (c.indexOf("next") == 0) {
var fragments = c.split("=");
if(fragments.length == 2 && !isNaN(fragments[1])) {
return parseInt(fragments[1]) + 1;
}
}
}
return "1";//default
}
function loadNextSeqToForm() {
var nextValue = getNextSeq();
document.cookie = "next=" + nextValue + ";";
document.getElementById("serial").value = formatToSixCharacters(nextValue);
}
function formatToSixCharacters(num) {
var numStr = num + "";
if(numStr.length < 6) {
var zeros = 6 - numStr.length;
for(var i = 1; i <= zeros; i++) {
numStr = "0" + numStr;
}
}
return numStr;
}
*/
//Solution 2: Using Session
function loadNextSeqToForm() {
var nextValue = sessionStorage.getItem("next") != null? sessionStorage.getItem("next") : 1;
document.getElementById("serial").value = formatToSixCharacters(nextValue);
sessionStorage.setItem("next", parseInt(nextValue) + 1)
}
function formatToSixCharacters(num) {
var numStr = num + "";
if(numStr.length < 6) {
var zeros = 6 - numStr.length;
for(var i = 1; i <= zeros; i++) {
numStr = "0" + numStr;
}
}
return numStr;
}
</script>
</html>
++ Code using PHP and MySQL
main-page.html
<html>
<head>
<title>Main Page</title>
</head>
<body>
<!-- Note this time we have to use PHP file reference -->
Print
</body>
</html>
form-1.php
<?php
session_start();
function getNextSequnceNumber() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "orders";
$nextSeq = 1;
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT next_seq FROM order_sequence";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($row = $result->fetch_assoc()) {
$nextSeq = $row["next_seq"];
}
}
//Update next sequence number in db
$sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
if (mysqli_query($conn, $sql)) {
//Updated successfully
//Write in log may be
}
$conn->close();
return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
DB Scripts
CREATE DATABASE orders;
USE orders;
CREATE TABLE order_sequence (
next_seq INT NOT NULL
);
-- DEFAULT VALUE
INSERT INTO order_sequence (next_seq)
VALUES(1);
Note: Make sure you replace your DB user name and password
SQLITE3 version of code as requested
form-sqlite.php
<?php
session_start();
class DBUtil extends SQLite3 {
function __construct() {
//Open db
$this->open("orders.db");
}
function createTableIfNotExists() {
//create table if not exists already
$sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
." next_seq INT NOT NULL"
.")";
$result = $this->exec($sql);
return $result;//Whether table created successfully or not
}
function updateNextSeqNumber($nextSeq) {
//update next sequnce number in db
$sql = "UPDATE order_sequence SET next_seq = ".$nextSeq;
$result = $this->exec($sql);
return $result;
}
function insertFirstTime() {
//insert first time
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
$result = $this->exec($sql);
return $result;
}
function getNextSeq() {
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$result = $this->query($sql);
$nextSeq = 1;
if($row = $result->fetchArray(SQLITE3_ASSOC)) {
$nextSeq = $row["next_seq"];
} else {
$this->insertFirstTime();//First sequence number, so that next update queries will be always successfull
}
$this->updateNextSeqNumber($nextSeq + 1);
return $nextSeq;
}
}
function getNextSequnceNumber() {
//Create new object of utility class
$db = new DBUtil();
if(!$db){
die("Connection failed: " . $db->lastErrorMsg());
}
//Check if connected
if($db->createTableIfNotExists()) {
$nextSeq = $db->getNextSeq();
return formatToSixCharacters($nextSeq);
} else {
die ("Error: " . $db->lastErrorMsg());
}
//close connection finally
$db->close();
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
++PHPDesktop With Sqlite Version
form-php-desktop-sqlite.php
Please include this PHPDesktop Helper file pdo.php provided by PHPDesktop. However this is small helper file, it does not serve big purpose, but it will help you for now.
Also read Using Sqlite with PHP Desktop
<?php
session_start();
include "./pdo.php";
function getNextSequnceNumber() {
//Open connection
$db_file = "./orders.sqlite3";
PDO_Connect("sqlite:$db_file");
//Create table if not exists
$sql = "CREATE TABLE IF NOT EXISTS order_sequence ("
." next_seq INT NOT NULL"
.")";
PDO_Execute($sql);
//get next sequence number
$sql = "SELECT next_seq FROM order_sequence";
$nextSeq = PDO_FetchOne($sql);
if($nextSeq == null) {
$nextSeq = 1;
//Also insert first time record
$sql = "INSERT INTO order_sequence (next_seq) VALUES (1)";
PDO_Execute($sql);
}
//Update next time sequence
$sql = "UPDATE order_sequence SET next_seq = ".($nextSeq + 1);
PDO_Execute($sql);
return formatToSixCharacters($nextSeq);
}
function formatToSixCharacters($num) {
$numStr = $num . "";
if(strlen($numStr) < 6) {
$zeros = 6 - strlen($numStr);
for($i = 1; $i <= $zeros; $i++) {
$numStr = "0" . $numStr;
}
}
return $numStr;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form Printing</title>
</head>
<body>
<form>
<input class="serial-no" type="text" name="fname" value="<?php echo getNextSequnceNumber() ?>" maxlength="6" size="6" readonly="readonly">
</form>
</body>
</html>
A really simple way to do this is by using jQuery. Use the click event listener with the button link which will listen to every clicks made to that button, and increment the value with each clicks. With the starting value as 000000, store the incremented value into a variable and then use that variable on a desired page.
FOR EXAMPLE:
Consider that you have this button on the home.html page:
BUTTON
Now, using jQuery - listen to the click events from this link and store the incremented values on variable like this:
var count = 0,
default = '000000';
$('#linkcounter').click(function(e) {
e.preventDefault();
count++;
var ctxt = '' + count;
var incrementval = pad.substr(0, pad.length - ctxt.length) + ctxt;
});
// store the value into the local storage of DOM for the current session. this is done to retain the variable value even after a page is refreshed.
var incrementvallocal = incrementval;
localStorage.setItem("incrementvalueper", incrementvallocal);
The incremented value stored in the variable incrementval is sent to the localstorage. Now just use the value of this variable on desired page(in this example it is formpage.html).
If you want to set the placeholder text on the form page which has an input field like this:
<input class="serial-no" type="text" name="fname" placeholder="000000" maxlength="6" size="6">
by the incremented value, then use this jQuery code:
// get incremented value from the local storage of DOM.
var getincval = localStorage.getItem("incrementvalueper");
$(document).ready(function(){
$('.serial-no').attr("placeholder", getincval);
});
This code uses the value of the variable getincval(which has the incremented click value) and sets it to the placeholder text of the input element which has the class .serial-no.
Let me know if this helps. :)
I have been struggling with this for a while now, I got some help from a similar question but I can't seem to make it work in my example.
I have an RSS feed on my website and what I am trying to do is display a message saying "No Warnings" when the RSS feed is blank/empty. If there is something in the RSS feed then I just want to show that.
For the life of me I can't get this to work! I can't get it to recognize the feed is blank...is this possible??
Here is my code,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Loading directly an RSS feed and displaying it</title></head>
<link type="text/css" href="rss-style.css" rel="stylesheet">
<body bgcolor="#FFE991">
<div id="zone" ><img src="/images/alert-icon-120.png" alt="Weather Warnings for SA. Issued by the Australian Bureau of Meteorology" align="left" style="padding-right: 4pt"width="15" height="15" border="0"/> Current South Australian Statewide Warnings:<small><em><font color="black"> Provided by The Bureau of Meteorology</font></em></small>
</div>
<fieldset class="rsslibbomsa">
<?php
require_once("rsslib.php");
$url = "http://www.bom.gov.au/fwo/IDZ00057.warnings_sa.xml";
$rss = RSS_Display($url, 15, false, false);
if ($rss == '')
{
// nothing shown, do whatever you want
echo 'No Current Warnings';
}
else
{
// something to display
echo $rss123;
}
?>
</fieldset>
</body>
</html>
If it helps RSS_Display is from the rsslib.php file, which I have provided below,
<?php
/*
RSS Extractor and Displayer
(c) 2007-2010 Scriptol.com - Licence Mozilla 1.1.
rsslib.php
Requirements:
- PHP 5.
- A RSS feed.
Using the library:
Insert this code into the page that displays the RSS feed:
<?php
require_once("rsslib.php");
echo RSS_Display("http://www.bom.gov.au/fwo/IDZ00059.warnings_vic.xml", 15);
? >
*/
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("pubDate");
$tnl = $tnl->item(0);
$date = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("description");
$tnl = $tnl->item(0);
$description = $tnl->firstChild->textContent;
$y["title"] = $title;
$y["link"] = $link;
$y["date"] = $date;
$y["description"] = $description;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size = 15)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title</li>\n";
}
$page .="</ul>/n";
return $page;
}
function RSS_Display($url, $size = 15, $site = 0, $withdate = 0)
{
global $RSS_Content;
$opened = false;
$page = "";
$site = (intval($site) == 0) ? 1 : 0;
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, $site, $size + 1 - $site);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<ul>\n";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$page .= "<li>$title";
if($withdate)
{
$date = $article["date"];
$page .=' <span class="rssdate">'.$date.'</span>';
}
$description = $article["description"];
if($description != false)
{
$page .= "<br><span class='rssdesc'>$description</span>";
}
$page .= "</li>\n";
if($type==0)
{
$page .="</b><br />";
}
}
if($opened == true)
{
$page .="</ul>\n";
}
return $page."\n";
}
?>
Any help would be much appreciated.
Many thanks.
If you look at the rsslib code, you see that if the rss has no articles, the returned string will be \n.
The test to check if the RSS is empty should be if ($rss == "\n")
In addition to this, rsslib seems to be an old code (2010) and it is not object oriented (this is a problem because there are global vars defined outside the functions which can be in conflict with your code.
Moreover, this class does all the formatting of the RSS so if you want to change it, you will need to change the rsslib code.
You should consider using an other class like this one : https://github.com/dg/rss-php which is object oriented and easy to use.
I am new to programming so this question of mine might seems irrelevant. I want to know how to hide and show a html element using the original JavaScript not jQuery. Since I'm a total beginner I think I have to learn the primitive JavaScript before jumping into some libraries like jQuery.
First of all I'll paste the code:
index.php
<html>
<head>
<script type="text/javascript" src="myscripts.js"></script>
<style type='text/css'>
#show_description {
min-height: 100px;
min-width: 500px;
max-height: 100px;
max-width: 500px;
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div>
<form name="myform" action="index.php" method="get" >
Select Year: <?php echo hspacer(1); ?>
<select id="year_list" name="year_list" onchange="check_year_event();" >
<?php
for($year = (date('Y') - 100); $year <= (date('Y') + 100); $year++ ) {
if ($year == date('Y')) echo "<option value='$year' name='$year' selected='' >" . $year . "</option>";
else echo "<option value='$year' name='$year' >" . $year . "</option>";
}
?>
</select>
<?php echo hspacer(5); ?>
Select Event: <?php echo hspacer(1); ?>
<select id="event_list" name="event_list" onchange="check_year_event();" >
<?php
$events = array("Karate Tournament", "Beauty Pageant", "Film Festival", "Singing Contest", "Wedding");
foreach($events as $event) echo "<option value='$event' name='$event' >" . $event . "</option>";
?>
</select>
<?php echo vspacer(2); echo hspacer(22); ?>
<input type="submit" id="add_description" value="Add Description" onclick="show(); "/>
</form>
</div>
<div id="show_description">
</div>
</body>
</html>
functions.php
<?php
function hspacer($num_of_spaces) {
$spaces = "";
if ($num_of_spaces > 0) for($i=0; $i<$num_of_spaces; $i++ ) $spaces .= " ";
return $spaces;
}
function vspacer($num_of_linefeeds) {
$linefeeds = "";
if ($num_of_linefeeds > 0) for($i=0; $i<$num_of_linefeeds; $i++ ) $linefeeds .= "<br />";
return $linefeeds;
}
?>
myscripts.js
function create2DArray(row, col){
var array2D = new Array(row);
for (var i = 0; i < row; i++) {
array2D[i] = new Array(col);
}
return array2D;
}
function check_year_event() {
var years_and_events = create2DArray(10, 3);
years_and_events[0][0] = 2001;
years_and_events[0][1] = "Karate Tournament";
years_and_events[0][2] = "Annual karate tournament held globally";
years_and_events[1][0] = 2002;
years_and_events[1][1] = "Beauty Pageant";
years_and_events[1][2] = "Beauty pageant held globally";
years_and_events[2][0] = 2003;
years_and_events[2][1] = "Film Festival";
years_and_events[2][2] = "Film festival held globally";
years_and_events[3][0] = 2004;
years_and_events[3][1] = "Singing Contest";
years_and_events[3][2] = "Singing contest tournament held globally";
years_and_events[4][0] = 2005;
years_and_events[4][1] = "Wedding";
years_and_events[4][2] = "Wedding tournament held globally";
years_and_events[5][0] = 2007;
years_and_events[5][1] = "Karate Tournament";
years_and_events[5][2] = "Annual karate tournament held globally";
years_and_events[6][0] = 2008;
years_and_events[6][1] = "Beaty Pageant";
years_and_events[6][2] = "Beauty pageant held globally";
years_and_events[7][0] = 2009;
years_and_events[7][1] = "Film Festival";
years_and_events[7][2] = "Film festival held globally";
years_and_events[8][0] = 2010;
years_and_events[8][1] = "Singing Contest";
years_and_events[8][2] = "Singing contest tournament held globally";
years_and_events[9][0] = 2011;
years_and_events[9][1] = "Wedding";
years_and_events[9][2] = "Wedding tournament held globally";
var year = document.getElementById('year_list').value;
var event = document.getElementById('event_list').value;
for (var i = 0; i < years_and_events.length; i++) {
if ((year == years_and_events[i][0]) && (event == years_and_events[i][1])) {
// This is where I want to put the command to show and hide the div with id = "show_description"
}
}
}
What I want to happen is that when the user changes the value of any of the select element it will automatically check if the combination exists. If there is, it will send the content of the array to the div and that's the only time the div will show.
I'm not pretty sure to what you looking for, some question aren't clear to me. If you say hide or show a div, you can change the style of the div.
//Using visibility
if(show){
document.getElementById('show_description').style.visibility = "visible";
} else {
document.getElementById('show_description').style.visibility = "hidden";
}
//Using display
.style.display = "block"; //To show
.style.display = "none"; //To hide
First, I'd be worried about using the var event, while not a reserve word future developers may get slightly off-balanced to see it in a non DOM-event usage.
Then to start your page off, set that div to visibility:hidden
<div id="show_description" style="visibility:hidden;"></div>
For the code:
var targetNode = document.getElementById('show_description');
var children = targetNode.childNodes;
for(var i=0,len=children.length;i<len;i++){
targetNode.removeChild(children[i]);
}
var newNode = document.createTextNode(year+" "+event);
targetNode.appendChild(newNode);
targetNode.style.visibility = 'visible';
Basically the above selects the div where you want the content to go. Then removes anything inside of it, lastly it creates a new text node of your selected year and event and appends that into the div.
I've found apples DOM script intro to be very helpful for pure js dom manipulating.