I am attempting to load a graph with options to show data between select dates. When I run it on my webpage, I get an error "Table has no columns." 1, but when i set the IF statement (buildchris) to NOT EQUAL to maincampus, the chart will load. I believe it has something to do with the xmlhttp .send, the variables seem to not be sending over POST (buildingchartchris). Does anyone have a solution to this problem?
buildchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$p = $_POST['purpose'];
if($p == "maincampus")
{
$sm = $_POST['sm'];
$sd = $_POST['sd'];
$sy = $_POST['sy'];
$em = $_POST['em'];
$ed = $_POST['ed'];
$ey = $_POST['ey'];
//$start_date = Date("Y-m-d", mktime(0, 0, 0, $sm, $sd, $sy));
//$end_date = Date("Y-m-d", mktime(0, 0, 0, $em, $ed, $ey));
$start_date= "2014-01-01";
$end_date= "2016-01-01";
$result = $dbc->query('SELECT SUM(actual_hours) as act_hours, Buildings.bld_name, Buildings.bld_location FROM work_orders INNER JOIN Buildings ON work_orders.building = Buildings.bld_no WHERE work_orders.actual_completion_date > "'.$start_date.'" AND work_orders.actual_completion_date < "'.$end_date.'" AND Buildings.bld_location ="0" AND Buildings.bld_name <> "N/A" AND work_orders.actual_completion_date IS NOT NULL GROUP BY Buildings.bld_name');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Building', 'type' => 'string'),
array('label' => 'Hours', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['bld_name']);
// Values of the each slice
$temp[] = array('v' => (int) $r['act_hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
}
?>
buildingchartchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$page_title = 'Dashboard';
include ('includes/header.html');
?>
<html>
<head>
<title>Dashboard</title>
<link rel="icon" href="images/NKU.png" type="image/png" sizes="16x16">
<link rel="stylesheet" href="includes/as.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js?libraries=geometry"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script>
<!--
//hides or shows the table given by nm
function hide_table(nm)
{
// alert(is_fullscreen);
var table_selector = "#table_" + nm;
$(table_selector).toggle();
//table_width = (table_width == 24)? 35:24;
//$("#iframeholder").animate({width: table_width + "%"});
}
// -->
</script> </head>
<div id="content">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Set a callback to run when the Google Visualization API is loaded.
// google.setOnLoadCallback(drawChart);
function drawChart() {
var maincamp_sm, maincamp_sd, maincamp_sy, maincamp_em, maincamp_ed, maincamp_ey;
if( document.getElementById("maincamp_dates_quarter").checked )
{
var maincamp_q = document.getElementById("maincamp_quarter").value;
maincamp_ey = Number(document.getElementById("maincamp_quarter_year").value);
maincamp_sy = maincamp_ey;
if( maincamp_q == 0 )
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
}
else if( maincamp_q == 1)
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 9;
maincamp_ed = 30;
}
else if( maincamp_q == 2 )
{
maincamp_sm = 10;
maincamp_sd = 1;
maincamp_em = 12;
maincamp_ed = 31;
}
else if( maincamp_q == 3 )
{
maincamp_sm = 1;
maincamp_sd = 1;
maincamp_em = 3;
maincamp_ed = 31;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
else if( maincamp_q == 4 )
{
maincamp_sm = 4;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
}
else
{
maincamp_sm = document.getElementById("maincamp_start_month").value;
maincamp_sd = document.getElementById("maincamp_start_day").value;
maincamp_sy = document.getElementById("maincamp_start_year").value;
maincamp_em = document.getElementById("maincamp_end_month").value;
maincamp_ed = document.getElementById("maincamp_end_day").value;
maincamp_ey = document.getElementById("maincamp_end_year").value;
}
if(!( (maincamp_ey < maincamp_sy) || ( (maincamp_em < maincamp_sm) && (maincamp_ey == maincamp_sy) ) || ( (maincamp_ed < maincamp_sd) && (maincamp_em == maincamp_sm) && (maincamp_ey == maincamp_sy) ) ))
{
var xmlhttp;
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()//Function called when there is a change of state for the server
{ //request
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)//when request is complete and no issues
{
//var str = xmlhttp.responseText;
var jsonData = $.ajax({
url: "buildchris.php",
type: "POST",
dataType: "json", // type of data we're expecting from server
async: false // make true to avoid waiting for the request to be complete
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData.responseText);
var options = {
title: 'Labor Hours for Main Campus',
is3D: 'true',
width: 1200,
height: 2000,
chartArea:{width:"40%"},
bar: {groupWidth: "50%"}
};
var maincamp_view = new google.visualization.DataView(data);
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(maincamp_view, options);
}
};
xmlhttp.open("POST","buildchris.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("purpose=maincampus&sm=" + maincamp_sm + "&sd=" + maincamp_sd + "&sy=" + maincamp_sy + "&em=" + maincamp_em + "&ed=" + maincamp_ed + "&ey=" + maincamp_ey);
}
else
{
alert("Your end date cannot be before the start date.");
}
}
google.load('visualization', '1', {'packages':['corechart']});
function cursor_hand(x)
{
x.style.cursor = "pointer";
}
function cursor_default(x)
{
x.style.cursor = "default";
}
function hide_element(nm)
{
var table_selector = "#" + nm;
$(nm).toggle();
}
</script>
<body>
<p onclick = "hide_element(operational_effectiveness_div);" style = "text-decoration: underline; font-size:x-large; font-weight:bold;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Operational Effectiveness Reports</p><br>
<div id = "operational_effectiveness_div" >
<p onclick = "hide_element(maincamp_div);" style = "text-indent: 15px; text-decoration: underline;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Show Total Labor Hours for Main Campus 2015-16</p><br>
<div id = "maincamp_div" style = "display:table;">
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_quarter" name = "maincamp_dates" value = "1" checked> Report by quarter </legend>
<p><select id = "maincamp_quarter">
<option value = 0 selected>All Quarters</option>
<option value = 1>Q1</option>
<option value = 2>Q2</option>
<option value = 3>Q3</option>
<option value = 4>Q4</option>
</select>
<input type = "number" id = "maincamp_quarter_year" min = "2015" value = "2015"></p>
</fieldset><br>
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_range" name = "maincamp_dates" value = "2"> Custom date range </legend>
<p>Start date (mm-dd-yyyy): <input type = "number" id = "maincamp_start_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_start_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_start_year" min = "2015" value = "2015"></p>
<p>End date (mm-dd-yyyy): <input type = "number" id = "maincamp_end_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_end_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_end_year" min = "2015" value = "2016"></p>
</fieldset>
<br>
<p onclick = "drawChart()" style = "border: thin solid black; padding: 2px; width: 95px; margin-left: 550px;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Generate report</p>
<div id="chart_div" style="width: 1000px; text-indent: 50px;"></div>
</div>
</div>
</body>
</html>
<?php
//Release the used resources
mysqli_close($dbc);
include ('includes/footer.html');
?>
Related
I have written a code to insert the values into the database table using ajax. If u see the image below ,the values are appeared in the text boxes and when pressed add areas button, these values must be added to the table.
image:
From the image, the values of X,Y,W and H are gathered and when the add areas button is clicked, it should insert the values of x,y,w and h in the table.
index.php:
<table>
<tr>
<div class="actions">
<input type="button" id="btnView" value="Display areas" class="actionOn" />
<input type="button" id="btnReset" value="Reset" class="actionOn" />
<input type="button" id="btn_add" value="add areas" class="actionOn" />
</div>
<br>
<div id="output" class='output'> </div>
</table>
<p>X:<input type= "text" id="x" name ="x" value="-">
<p>Y:<input type= "text" id="y" name ="y" value="-">
<p>W:<input type= "text" id="w" name ="w" value="-">
<p>H:<input type= "text" id="h" name ="h" value="-">
<script>
var selectionExists;
function areaToString (area) {
document.getElementById('x').value = area.x;
document.getElementById('y').value = area.y;
document.getElementById('w').value = area.width;
document.getElementById('h').value = area.height;
return (typeof area.id === "undefined" ? "" : (area.id + ": ")) + area.x + ':' + area.y + ' ' + area.width + 'x' + area.height + '<br />'
}
$('#btn_add').click(function(){
var x_value= document.getElementById('x').value;
var y_value= document.getElementById('y').value;
var w_value= document.getElementById('w').value;
var h_value= document.getElementById('h').value;
$.ajax({
type:'POST',
url: 'server.php',
data:{
'x_value': x_value,
'y_value': y_value,
'w_value': w_value,
'h_value': h_value
},
success: function(data){
alert("x:" + x_value +"y:" +y_value+"w:" +w_value+"h:" +h_value);
}
});
});
function output (text) {
$('#output').html(text);
}
// Log the quantity of selections
function debugQtyAreas (event, id, areas) {
console.log(areas.length + " areas", arguments);
};
// Display areas coordinates in a div
function displayAreas (areas) {
var text = "";
$.each(areas, function (id, area) {
text += areaToString(area);
});
output(text);
};
</script>
Server.php:
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'project_focus');
if(isset($_POST['x_value'])){
$x= $_POST['x_value'];
$valid="SELECT * FROM sample";
$validdb=mysqli_query($db, $valid);
while (mysqli_fetch_array($validdb)){
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
}
}
?>
The database table name is sample and its fields are id, x_value, y_value , w, h.
The server.php is the file where i tried to use the mysql query to insert the values into the table. but when i run the code, the output is not achieved. The insert values did not work. I think i made some mistake with the query i think. but i couldnt figure it out. Can someone help me fix this problem.
Did you try to remove the while clause?
You shouldn't need to first query the database in order to do the insert. Just executing the connect and insert commands should work.
Be sure that the other columns in the table are not required, and are set as DEFAULT NULL, so that the query doesn't error on other columns not being set in your insert.
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
HTML, CSS, and JavaScript should be more like
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, aC, rC, tC, shuffle, rand; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
shuffle = array=>{
let a = array.slice(), i = a.length, n, h;
while(i){
n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
}
return a;
}
rand = (min, max)=>{
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
// magic below
const x = I('x'), y = I('y'), w = I('w'), h = I('h'), display = I('display');
const reset = I('reset'), add = I('add'), error = I('error');
function valid(){
let xv = x.value, yv = y.value, wv = w.value, hv = h.value;
if(xv === '' || isNaN(xv) || yv === '' || isNaN(yv) || wv === '' || isNaN(wv) || hv === '' || isNaN(hv)){
error.textContent = 'Invalid Number';
return false;
}
error.textContent = ''; return true;
}
x.oninput = y.oninput = w.oninput = h.oninput = ()=>{
valid();
}
display.onclick = ()=>{
const fd = new FormData; fd.append('get_xywh', true);
post('xywh.php', fd, data=>{
output.innerHTML = '';
data.xywh.forEach(o=>{
const sect = M('div'), sx = M('div'), sy = M('div'), sw = M('div');
const sh = M('div');
sx.textContent = 'X: '+o.x; sy.textContent = 'Y: '+o.y;
sw.textContent = 'W: '+o.w; sh.textContent = 'H: '+o.h; sect.appendChild(sx);
sect.appendChild(sy); sect.appendChild(sw); sect.appendChild(sh);
output.appendChild(sect);
});
});
}
reset.onclick = ()=>{
x.value = y.value = 0; w.value = h.value = 1; error.textContent = '';
}
add.onclick = ()=>{
if(valid()){
const fd = new FormData;
fd.append('x', x.value); fd.append('y', x.value); fd.append('w', w.value);
fd.append('h', h.value);
post('xywh.php', fd, json=>{
error.textContent = json.success ? 'Hacker' : 'Content Added';
});
}
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body,.main{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
.er{
color:#900;
}
#xywh{
display:flex; flex-wrap:wrap; align-content:top center;
}
#xywh>*{
margin-bottom:7px;
}
#xywh>label{
flex:0 5%; text-align:center; padding-top:3px;
}
input{
padding:3px 5px; border:0;
}
input[type=number]{
border-radius:3px;
}
#xywh>input{
flex:0 95%;
}
.main{
text-align:center;
}
.main>input[type=button]{
background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 14px Tahoma, Geneva, sans-serif; padding:5px 10px; border-radius:5px;
}
#error{
margin-top:5px;
}
#output{
background:#000; color:#0c0; text-align:left; padding:5px 10px; margin:15px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>index.php</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='xywh'>
<label for='x'>X:</label><input id='x' type='number' min='0' value='0' />
<label for='y'>Y:</label><input id='y' type='number' min='0' value='0' />
<label for='w'>W:</label><input id='w' type='number' min='1' value='1' />
<label for='h'>H:</label><input id='h' type='number' min='1' value='1' />
</div>
<input id='display' type='button' value='Display Areas' />
<input id='reset' type='button' value='RESET' />
<input id='add' type='button' value='Add Area' />
<div id='error' class='er'></div>
<div id='output'>No Data Requested</div>
</div>
</body>
</html>
Put your MySQL connect.php in a restricted folder with permission 700.
<?php /* restricted/connect.php */
$db = #new mysqli('host', 'username', 'password', 'database');
?>
Let's say you have the following table made in MySQL like:
`CREATE TABLE xywh(
x INT NOT NULL,
y INT NOT NULL,
w INT NOT NULL,
h INT NOT NULL
)ENGINE=InnoDB;`
Now in a folder with the normal permission 755 (directly in your site root in this case)
<?php /* xywh.php */
if(!isset($_SERVER['HTTPS'])){ // force https or comment out if no https - but why are you making a site with no https?
header('LOCATION:https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); die;
}
$o = new StdClass;
if(isset($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'])){
$x = $_POST['x']; $y = $_POST['y']; $w = $_POST['w']; $h = $_POST['h'];
$r1 = '/^(0|[1-9]+[0-9]*$/'; $r2 = '/^[1-9]+[0-9]*$/';
if(!preg_match($r1, $x) || !preg_match($r1, $y) || !preg_match($r2, $w) || !preg_match($r2, $w)){
$o->hacker = true;
}
else{
require_once 'restricted/connect.php';
$s = $db->prepare('INSERT xywh (x, y, w, h) VALUES (?, ?, ?, ?)');
$s->bind_param('iiii', $x, $y, $w, $h); $s->execute(); $s->close(); $db->close();
$o->success = true;
}
}
elseif($_POST['get_xywh']) && $_POST['get_xywh'] === true){
require_once 'restricted/connect.php'; $a = [];
if($q = $db->query('SELECT x, y, w, h FROM xywh')){
while($r = $q->fetch_object()){
$a[] = $r;
}
$q->close();
}
$o->xywh = $a; $db->close();
}
else{
$o->hacker = true;
}
echo json_encode($o);
?>
Note that this is a very crude and simple example. You should have users that are allowed to input the data. So, you need a login that verifies users first. It's much more work. Also, this example just INSERTs a new row no matter if one exists that is the same... which, is what you would want if there is more than one of the same. If not, you'll have to test for sameness with a WHERE condition, and do an UPDATE if it already exists. Make sure you use prepared statements, unless you are doing very simple queries. Good Luck... this might take a while to understand. It's mostly an AJAX example for you.
After user select location,in the next select option which is select car, will show list of car in selected location..The list of car retrieved direct from database..So i need to display all the car list in that area and need to disable enable the car list according the condition which is if the car id is not available the option value will disabled..and the option value become enable if car id is available..
<?php
$car = "SELECT *,location_master.location_id , location_master.location_name,
appcarinfo.loc_id_ext, appcarinfo.location ,appcarinfo.model ,appcarinfo.noplat FROM location_master
INNER JOIN appcarinfo ON
appcarinfo.lat = location_master.gmaplat
AND
appcarinfo.lon = location_master.gmaplng
where appcarinfo.model='".$fetchres['idmodel']."' ";
$qcar = mysqli_query($conn, $car);
?>
<option disabled value="" selected hidden>Please Select Car</option>
<?php
while ($showcar= mysqli_fetch_array($qcar))
{
if ($showcar['car_id']=="Available")
{
?>
<option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" enabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
else
?> <option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" disabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
?>
</select>
SELECT OPTION
I'm also new to AJAX..how to pass data and retrieve it back to select option
//check availability car
function check_availability()
{
//id from form
var reservation1 = document.getElementById("reservation");
var pickup_date = document.getElementById("pickup_date").value;
var return_date = document.getElementById("return_date").value;
var pickup_time = document.getElementById("pickup_time").value;
var return_time = document.getElementById("return_time").value;
var carID= document.getElementById("carID").value;
$.ajax({
type : "POST",
url : "function/check_car_availability.php",
data : {
pickup_date : pickup_date,
return_date : return_date,
pickup_time : pickup_time,
return_time : return_time,
carID : carID,
},
dataType : "JSON",
success : function(data) {
$('#edt_pickup').val(data.edt_pickup);
$('#edt_return').val(data.edt_return);
$('#msgCheck').html(data.msgCheck);
$('#btn_proceed').html(data.btn_proceed);
}
});
}
check_car_availability.php
<?php
if ($_POST['pickup_date'])
{
$pickup_date = $_POST['pickup_date'];
$return_date = $_POST['return_date'];
$pickup_time = $_POST['pickup_time'];
$return_time = $_POST['return_time'];
$car_id = $_POST['car_id'];
$owner_id = $_POST['owner_id'];
//convert normal date to epoch
$pickup_date1 = explode("/",$pickup_date);
$return_date1 = explode("/",$return_date);
$pickup_time1 = explode(":",$pickup_time);
$return_time1 = explode(":",$return_time);
//hour, minute, second, month, day, year
$edt_pickup = mktime($pickup_time1[0],$pickup_time1[1],0,$pickup_date1[1],$pickup_date1[0],$pickup_date1[2]);
$edt_return = mktime($return_time1[0],$return_time1[1],0,$return_date1[1],$return_date1[0],$return_date1[2]);
//convert from d/m/Y to Y-m-d
$pickup_date_2 = $pickup_date1[2]."-".$pickup_date1[1]."-".$pickup_date1[0];
$return_date_2 = $return_date1[2]."-".$return_date1[1]."-".$return_date1[0];
//keluarkan tarikh yg customer pilih ada tak dlm booking master
$chkBooked = mysqli_query($conn, "SELECT count(car_id) AS countid FROM appbooking WHERE
((start_rent >= '$edt_pickup' AND end_rent <= '$edt_return')
OR (((start_rent <= '$edt_pickup' AND end_rent >= '$edt_return')))
OR (((end_rent >= '$edt_pickup' AND end_rent <= '$edt_return')))
OR (((start_rent >= '$edt_pickup' AND start_rent <= '$edt_return')))) AND car_id = '$car_id' AND status !='0'");
$fetchBooked = mysqli_fetch_array($chkBooked);
if($fetchBooked['countid'] != 0) //kalau ada show not available
{
$availability = "Not Available";
$available_count = 0;
} else //kalau tak de show available
{
$availability = "Available";
$available_count = 1;
}
//keluarkan car details
$carDetails = mysqli_query($conn, "SELECT * FROM appcarinfo WHERE car_id = '$car_id'");
$fetchchkowner = mysqli_fetch_array($carDetails);
//kalau manual availability check ada tak date dlm range yg owner dah set
$sql = mysqli_query($conn, "SELECT count(car_availability.availability_id) AS cntAvail FROM appcarinfo INNER JOIN car_availability ON car_availability.car_id = appcarinfo.car_id WHERE appcarinfo.car_id = '$car_id' AND car_availability.start_available <= '$edt_pickup' AND car_availability.end_available >= '$edt_return'");
$fetch = mysqli_fetch_array($sql);
if ($fetchchkowner['custom_availability'] == 1) //if owner set manual availability
{
if ($fetch['cntAvail'] > 0) //kalau ada
{
$avail = 1;
} else //kalau tak de
{
$avail = 0;
}
} else //if owner set auto availability
{
$avail = 1;
}
//check if this is klezcar car
if($fetchchkowner["owner_id"] == "0")
{
$klezcar_loc_id = $fetchchkowner["loc_id_ext"];
//check availability for blocked date klezcar
$sqlBlock = "SELECT * FROM `blocked_date_klezcar` where (
('".$pickup_date_2."' > startdate and '".$pickup_date_2."' < enddate)
or ('".$return_date_2."' > startdate and '".$return_date_2."' < enddate)
or ('".$pickup_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
or ('".$return_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
) and (location=0 or location=".$klezcar_loc_id.") order by location desc limit 1";
$queryBlock = mysqli_query($conn,$sqlBlock);
if(mysqli_num_rows($queryBlock) > 0)
{
$resBlock = mysqli_fetch_object($queryBlock);
$avail = 0;
$klezcar_blocked = 1;
$klezcar_blocked_reason = $resBlock->reason;
}
else
{
$klezcar_blocked = 0;
}
}
//calculation price rate
include 'calculation_price/calculationprice.php';
$encry = md5($edt_pickup.$edt_return.$total_pay.$total_rate.floor($day).$bhourplus.$car_id.$owner_id.$secretAuth);
//combine appbooking & car availability variable
if ($avail == 1 && $available_count == 1)
{
$availStatus = "<div class='alert alert-success'>You are good, car available.<br>Rental Price : Total <span style='font-size:20px; font-weight: bold;'>".number_format($total_pay,2)."</span> for ".floor($day)." day(s) ".$bhourplus." hour(s)</div>";
$btn_proceed = "<a href='confirmbooking.php?pickupdate=".$edt_pickup."&returndate=".$edt_return."&totalpay=".$total_pay."&totalrate=".$total_rate."&bookday=".floor($day)."&bookhour=".$bhourplus."&carid=".$car_id."&ownerid=".$owner_id."&encry=".$encry."' class='btn btn-primary'>Proceed</a>";
} else
{
$availStatus = "<div class='alert alert-danger'>We are sorry, car not available. Please refer Available & Not available date table.</div>";
$btn_proceed = "";
if($klezcar_blocked === 1)
{
$availStatus = "<div class='alert alert-danger'>".$klezcar_blocked_reason."</div>";
$btn_proceed = "";
}
}
/* *** SPECIAL FOR RAYA 2019 *** */
$start_blocked_date = "2019-06-04";
$end_blocked_date = "2019-06-09";
if( ($pickup_date_2 >= $start_blocked_date && $pickup_date_2 <= $end_blocked_date)
|| ($return_date_2 >= $start_blocked_date && $return_date_2 <= $end_blocked_date)
|| ($pickup_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date)
|| ($return_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date))
{
$availStatus = "<div class='alert alert-danger'>The date has been marked as Hari Raya Aidlifitri holiday session. We accept minimum rental of 7 days and above only. Please re-select date at least 3/6/2019 - 10/6/2019.</div>";
$btn_proceed = "";
}
/* *** SPECIAL FOR RAYA 2019 *** */
//return value
$data['edt_pickup'] = $edt_pickup;
$data['edt_return'] = $edt_return;
$data['msgCheck'] = $availStatus;
$data['btn_proceed'] = $btn_proceed;
$data['total_rate'] = $total_rate;
$data['total_pay'] = $total_pay;
$data['no_day_booking'] = floor($day);
$data['no_hour_booking'] = $bhourplus;
echo json_encode($data);
}
?>
How to save rotated image and text coordinates to database and print image in same angle? I am trying to save image also text and show in result image.
<!-- jQuery 2.2.3 -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="plugins/fabricjs/fabric.min.js"></script>
<!-- Fabric Script new -->
<script>
var canvas = new fabric.Canvas('can');
canvas.on({
'object:scaling': function(p){
if (p.target.scaleX < 1)
p.target._objects[1].scaleX = 1 + (1 -p.target.scaleX )
else
p.target._objects[1].scaleX = 1 / (p.target.scaleX)
if (p.target.scaleY < 1)
p.target._objects[1].scaleY = 1 + (1 -p.target.scaleY)
else
p.target._objects[1].scaleY = 1 / (p.target.scaleY)
canvas.renderAll()
},
});
//canvas.add(profilepic);
var photoCan = new Array(12);
for(var j=0 ; j<12 ; j++) {
photoCan[j] = photoGroup("User "+ (j+1));
}
var textCan = new Array(12);
for(var j=0 ; j<12 ; j++) {
textCan[j] = textGroup("Textbox "+ (j+1));
}
function photoGroup (text,x,y,w,h) {
w = w || 200; //defaults
h = h || 200;
x = x || 150;
y = y || 100;
var profilepic = new fabric.Rect({
originX: 'center',
originY: 'center',
fill: "#000",
strokeDashArray: [5, 5],
stroke: '#fff',
width: w,
height: h
});
var text = new fabric.Text(text, {
fontSize: 30,
fill: "#fff",
originX: 'center',
originY: 'center',
});
var group = new fabric.Group([ profilepic, text ], {
left: x,
top: y,
angle: 0
});
group.lockRotation = false;
group.lockUniScaling = false;
return group;
}
function textGroup (text,x,y,w,h) {
w = w || 300; //defaults
h = h || 200;
x = x || 150;
y = y || 100;
var profilepic = new fabric.Rect({
originX: 'center',
originY: 'center',
fill: "#2e2e2e",
strokeDashArray: [5, 5],
stroke: '#fff',
width: w,
height: h,
});
var text = new fabric.Text(text, {
fontSize: 30,
fill: "#fff",
originX: 'center',
originY: 'center',
});
var group1 = new fabric.Group([ profilepic, text ], {
left: x,
top: y,
angle: 0,
lockUniScaling: false,
});
group1.lockRotation = false;
group1.lockUniScaling= false;
return group1;
}
</script>
<!-- new script -->
<script>
$('document').ready(function() {
//hide add more buttons
$(".addButtons").hide();
$(".removeButtons").hide();
$("#myDropzonef").hide();
//**********************************Important: Show addButtons if already number is specified***********
//vars to get num of elements
var photonum = 0;
var textnum = 0;
//vars to get MAX
var phototot = 12;
var texttot = 12;
// Add more photos
$('#addmorephotos').click(function () {
addPhotoField();
});
// Add more Text
$('#addmoretext').click(function () {
addTextField();
});
// REMOVE BUTTONS
// Remove last photo
$("#removelastphoto").click(function () {
canvas.remove(photoCan[photonum-1]);//remove from canvas
$('#userphotogrp'+(photonum-1)).remove(); //remove from options
photonum--; //subtract the number
if(photonum<=1) $("#removelastphoto").hide(); //remove the button if less than num
});
// Remove last Text
$("#removelasttext").click(function () {
canvas.remove(textCan[textnum-1]);//remove textarea from canvas
$('#textgrp'+(textnum-1)).remove(); //remove from options
textnum--; //subtract the number
if(textnum<=1) $("#removelasttext").hide(); //remove the button if less than num
});
//checked or unchecked photos checkbox
$('#addPhotosCheck').change(function() {
if(this.checked) {
//checked
addPhotoField();
$("#addmorephotos").show();
} else {
//unchecked
var returnVal = confirm("This will remove the entered data?");
$(this).prop("checked", !returnVal);
if(returnVal) {
$('#photoslist').html(''); //remove all divs inside list
$("#addmorephotos").hide();
$("#removelastphoto").hide(); //remove remove button
for(var k=0; k<phototot ; k++) {
canvas.remove(photoCan[k]); //Remove all photos from canvas
}
photonum = 0; //reset value of photo number
}
}
});
//checked or unchecked BG checkbox
$('#addBgCheck').change(function() {
if(this.checked) {
$("#myDropzonef").show();
$(".morfchoice").show();
} else {
$("#myDropzonef").hide(); //*********************************also delete the female files
$(".morfchoice").hide();
}
});
//checked or unchecked Text checkbox
$('#addTextCheck').change(function() {
if(this.checked) {
//checked
addTextField();
$("#addmoretext").show();
} else {
//unchecked
var returnVal = confirm("This will remove the entered data?");
$(this).prop("checked", !returnVal);
if(returnVal) {
$('#textlist').html(''); //remove all divs inside list
$("#addmoretext").hide();
$("#removelasttext").hide(); //remove remove button
for(var k=0; k<texttot ; k++) {
canvas.remove(textCan[k]); //Remove all photos from canvas
}
textnum = 0; //reset value of photo number
}
}
});
function addPhotoField(){
if(photonum<phototot) {
$('#photoslist').append(`<div class="well"><div class="form-group" id="userphotogrp`+photonum+`" ><hr><h2>`+(photonum+1)+`</h2>
<label for="userphoto`+photonum+`">Photo type</label>
<select class="form-control userphotos" id="userphoto`+photonum+`">
<option>User Photo</option>
<option>Friend Photo</option>
<option>Friend Photo (Opposite gender)</option>
</select>
</div></div>`);
canvas.add(photoCan[photonum]); // add photo to canvas
if(photonum>0) {$("#removelastphoto").show(); }//show the "remove last" button
photonum++;
} else {
alert("You can only add upto "+phototot+ " Photos");
}
}
function addBgField(){
if(bgnum<bgtot) {
$('#backgroundlist').append(`<div class="well">
<div class="form-group" id="bggrp`+bgnum+`" ><hr><h2>`+(bgnum+1)+`</h2>
<label for="bg`+bgnum+`">Upload an image</label>
<input type="file" class="form-control-file" id="bg`+bgnum+`" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Prefered resolution is 800x420px</small>
</div>
<div class="form-group">
<label for="userphotos">Show to:</label>
<select class="form-control userphotos" id="userphotos">
<option>Common</option>
<option>Male</option>
<option>Female</option>
</select>
</div></div>`);
if(bgnum>0) $("#removelastbg").show();
bgnum++;
} else {
alert("You can only add upto "+bgtot+ " Backgrounds");
}
}
function addTextField(){
if(textnum<texttot) {
$('#textlist').append(`<div class="well">
<div class="form-group" id="textgrp`+textnum+`" ><hr><h2>`+(textnum+1)+`</h2>
<label for="text`+textnum+`">Add text line by line</label>
<textarea class="form-control" id="text`+textnum+`" rows="3"></textarea>
</div>
<div class="form-group">
<label for="showto`+textnum+`">Show to:</label>
<select class="form-control userphotos" id="showto`+textnum+`">
<option>Common</option>
<option>Male</option>
<option>Female</option>
</select>
</div>
<div class="form-group">
<label for="style`+textnum+`">Text Style:</label>
<select class="form-control chosen-select" id="style`+textnum+`">
<?php foreach($styles as $style) {
echo "<option>$style[0]</option>\n";
} ?>
</select>
</div></div>`);
$(".chosen-select").chosen(); //change select fields to chosen
$('.chosen-container').css('width', '100%'); //some bug fix for chosenjs
canvas.add(textCan[textnum]); // add photo to canvas
if(textnum>0) $("#removelasttext").show();
textnum++;
} else {
alert("You can only add upto "+texttot+ " TextFields");
}
}
//SUBMIT CODE AJAX
$("#finalSubmit").click(function () {
$(".overlay").show(); //show loading
var formData = new Object();
formData.slug = slug; //set slug to post variable
formData.photos = {};
formData.text = {};
formData.token = "<?php echo $token; ?>";
var numofphotos = photonum;
var numoftext = textnum;
var phototype = 0; // type of photo -> [user,friend,opp gender friend] => [0,1,2]
var textshowto = 0; // whom to show the text -> [common, male, female] => [0,1,2]
var textval = ""; //value of text field
var textstyle = ""; //value of text style
var x,y,h,w,str = "";
//photos
for(var i =0 ; i < numofphotos ; i++ ) {
phototype = document.getElementById("userphoto"+i).selectedIndex;
x = Math.floor(photoCan[i].left);
y = Math.floor(photoCan[i].top);
w = Math.floor(photoCan[i].getWidth());
h = Math.floor(photoCan[i].getHeight());
str = phototype + "," + x + "," + y + "," + w + "," + h;
formData.photos[i] = str;
}
//text
for(var i =0 ; i < numoftext ; i++ ) {
textshowto = document.getElementById("showto"+i).selectedIndex;
textval = document.getElementById("text"+i).value;
textval = textval.trim(); //remove leading or trailing whitespaces
textstyle = $("#style"+i+" option:selected").val();
x = Math.floor(textCan[i].left);
y = Math.floor(textCan[i].top);
w = Math.floor(textCan[i].getWidth());
h = Math.floor(textCan[i].getHeight());
str = textstyle + "," + textshowto + "," + x + "," + y + "," + w + "," + h;
formData.text[i] = {"value" : textval, "prop" : str};
}
var dataToSend = JSON.stringify(formData);
console.log(dataToSend);
$.ajax({
url: 'edit-ajax.php',
type: 'POST',
data: {"data" : dataToSend},
success: function( data, textStatus, jQxhr ){
$(".overlay").hide();
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
//Load from previous
$(".overlay").show();
<?php
//load pre photos
$i = 0;
$prop = Array();
foreach ($photos as $photo) {
$prop = str_getcsv($photo["prop"]);
echo "$('#addPhotosCheck').prop('checked', true);";
echo '$("#addmorephotos").show();';
echo 'photoCan['.$i.'].top = '.$prop[2].';';
echo 'photoCan['.$i.'].left = '.$prop[1].';';
echo 'photoCan['.$i.'].scaleToHeight('.$prop[4].');';
echo 'photoCan['.$i.'].scaleToWidth('.$prop[3].');';
echo 'addPhotoField();';
echo 'document.getElementById("userphoto'.$i.'").selectedIndex = '.$prop[0].";";
$i++;
}
?>
<?php
$i = 0;
$prop = Array();
foreach ($text as $txt) {
$prop = str_getcsv($txt["prop"]);
echo "$('#addTextCheck').prop('checked', true);";
echo '$("#addmoretext").show();';
echo 'textCan['.$i.'].top = '.$prop[3].';';
echo 'textCan['.$i.'].left = '.$prop[2].';';
echo "textCan[{$i}].setScaleX({$prop[4]}/textCan[{$i}].getWidth());";
echo "textCan[{$i}].setScaleY({$prop[5]}/textCan[{$i}].getHeight());";
echo 'addTextField();';
echo 'document.getElementById("showto'.$i.'").selectedIndex = '.$prop[1].";";
echo '$("#style'.$i.'").val("'.$prop[0].'");';
echo '$(".chosen-select option:contains(Base)").prop("selected","selected");';
echo '$(".chosen-select").trigger("chosen:updated");';
echo '$("#text'.$i.'").text(`'.$txt['data'].'`);';
$i++;
}
?>
canvas.renderAll();
$(".overlay").hide();//stop loading
}); //document.ready end
</script>
How to save rotated image and text coordinates to database and print
image in same angle? I am trying to save image also text and show in
result image.
Use canvas.toJSON() it will convert all the canvas data to json. Send that data to db. And when loading from db use canvas.loadFromJSON(). You no need to store the data from array and load it.
This is the code i'm using:
<?php
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($"http://newsxpressmedia.com/files/radar-simulation-files")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
$files[] = $file;
$curimage++;
}
}
closedir($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
#Timer_Countdown{
background:black;
color:yellow;
font-weight:bold;
text-align:center;
}
</style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
var images = <?=json_encode($files)?>;
//var images = [];
var x = -1;
var swap_hours = 0;
var swap_minutes = 0;
var swap_seconds = 5;
var down_counter_hours;
var down_counter_minutes;
var down_counter_seconds;
function initTimer() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
counter = setInterval(switcher, 1000);
}
function restartCounter() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
}
function switcher() {
down_counter_seconds--;
if (down_counter_hours <= 0 && down_counter_minutes <= 0 && down_counter_seconds <= 0) {
swapColor();
restartCounter();
}
if (down_counter_seconds <= 0 && down_counter_minutes > 0) {
down_counter_seconds = 60;
down_counter_minutes--;
}
if (down_counter_minutes <= 0 && down_counter_hours > 0) {
down_counter_minutes = 60;
down_counter_hours--;
}
document.getElementById("Timer_Countdown").innerText = down_counter_hours+":"+down_counter_minutes+":"+down_counter_seconds;
}
function swapColor() {
displayNextImage();
}
</script>
<div id="div_hours" class="div_box"></div>
<div id="div_minutes" class="div_box"></div>
<div id="div_seconds" class="div_box"></div>
<div id="div_switcher" class="div_box"></div>
</head>
<body onload = "initTimer()">
<div id="Timer_Countdown"> </div>
<img id="img" src="http://newsxpressmedia.com/files/theme/radar000005.Gif">
<button onclick="displayPreviousImage(); restartCounter()">Previous</button>
<button onclick="displayNextImage(); restartCounter()">Next</button>
</body>
</html>
The error is on the line:
var images = <?=json_encode($files)?>;
If i change this line to this line:
var images = [];
Then the code is working fine but without using the php files variable.
Something is wrong with the line: var images = <?=json_encode($files)?>;
I tried to change this line to: echo json_encode($images); or to var images = echo json_encode($files); but same error.
I'm using weebly to build my site and my site server is on ipage.com
How can i fix the error ?
It looks like you don't have short tags enabled(and are using a pre 5.4 php version), thus the line <?=json_encode($files)?> is not parsed by php and is just send straight through. var images = <... is not a valid javascript expression. Here's some information about php's short_open_tag parameter: http://php.net/manual/en/ini.core.php#ini.short-open-tag
A couple of changes. Change
$pattern ="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)";
to
$pattern = '/\.(png|jpg|jpeg|gif)$/i';
and
eregi($pattern, $file)
to
preg_match($pattern, $file)
and see what happens. eregi deprecated as PHP 5.3.0.
You are using '=' inside the PHP tags. Try this:
var images = <?json_encode($files)?>;
The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}