Select data from oracle and draw a chart using Google charts? - javascript

I want to select data from oracle and draw the chart but when I run the my code nothing else drawed.new3.php:
$tns2 = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SID = CLUSTDB1)))";
if ($conn = oci_connect("CAKTAS","******", $tns2)) {
echo "";
$stid = oci_parse($conn, "select wonum,STATUS, trunc( (sysdate-STATUSDATE) ) || 'd ' || trunc( mod((sysdate-STATUSDATE)*24,24) ) || ':' || trunc( mod( (sysdate-STATUSDATE)*24*60, 60 ) ) from maximo.WORKORDER_IT_VIEW where VFOPMGRGRP = 'IS_PRICHARHG' and STATUS <> 'COMPLETE' and STATUS <> 'CLOSE'");
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo json_encode($row);
} else {
die("could not connect to Maximo DB");
}
And it gives me correct array.
My html code:
<html>
<head>
<title>Kometschuh.de Tracker</title>
<!-- Load jQuery -->
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "new3.php", //my getting data php file
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Kometschuh.de Trackerdaten'
};
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
but in browser, I couldnt any chart

Refer my blog: http://howdyharish.wordpress.com/2014/08/11/create-google-charts-using-php-and-oracle-database/#more-3
Here is the code.
Index.php
<?php
ini_set(‘max_execution_time’, 123456);
$conn=oci_connect(‘username‘,’password‘,’DBname‘);
If (!conn)
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query= oci_parse($conn, “select col1, col2 from tablename“);
oci_execute($query);
$rows = array();
$table = array();
$table['cols'] = array(
array(‘label’ => ‘col1‘, ‘type’ => ‘string‘),
array(‘label’ => ‘col2‘, ‘type’ => ‘number‘),
);
$rows = array();
while($r = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
$temp = array();
//The below col names have to be in upper caps.
echo $r["COL1"];
$temp[] = array(‘v’ => (string) $r["COL1"]);
$temp[] = array(‘v’ => (int) $r["COL2"]);
$rows[] = array(‘c’ => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//Use the line below to see the data in jason format
//echo $jsonTable;
//Use the below lines of code to see data in a HTML table
/*echo “<table border=’1′ >\n”;
echo “<tr><th>col1</th><th>col2</th></tr>\n”;
while ($row = oci_fetch_array($query, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo “<tr>\n “;
foreach ($query as $block) {
echo ” <td>” . ($block !== null ? htmlentities($block, ENT_QUOTES) : “ ”) . “</td>\n”;
}
echo “</tr>\n”;
}
echo “</table>\n”; */
?>
//In head section
<!–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”>
google.load(‘visualization’, ‘1’, {‘packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: ‘name of the chart‘,
is3D: ‘true’,
width: 1000,
height: 600,
fontName: ‘Times-Roman‘,
fontSize: 23,
hAxis: {textStyle: {
fontName: ‘Times-Roman‘,
fontSize: ‘25‘ }}
};
//To create a line chart
var chart = new google.visualization.LineChart(document.getElementById(‘chart_div’));
chart.draw(data, options);
//To create a column chart
var chart2 = new google.visualization.ColumnChart(document.getElementById(‘chart_div2′));
chart2.draw(data, options);
}
</script>
// In body section
<!–this is the div that will hold the pie chart–>
<div id=”chart_div” ></div>
<div id=”chart_div2″ ></div>

You cannot just use json_encode, the PHP output needs to be in the format that the Google API will understand (Google Documentation Here). So basically, you need to have some kind of function in php that transforms the OCI results into a JSON string readable by Google.
I have published a solution that works pretty well in my setup, other users might benefit from it. You can see my code on GitHub:
https://github.com/ernestomonroy/PHP-for-Google-Visualization-API
The php code looks as folows:
<?php
/*
* #author Ernesto Monroy <ehmizmg#gmail.com>
* #version 1.0
* This function takes the Connection Details and the SQL String and creates an two arrays, one for the column info
* and one for the row data. This is then passed to the arrayToGoogleDataTable that builds and outputs the JSON string
*
* Input for this is:
* $un: User Name
* $pw: Password
* $db: Connection String for the DB
* (e.g. '(DESCRIPTION=(CID=MyDB)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SID=MyDB)))' )
* (tip, if you are running your PHP and Oracle Instance on the same server 127.0.0.1 should be used)
*
* WARNINGS:
* -I have not included any Oracle Error Handling
* -I have not included any row limit, so if your query returns an unmanageable amount of rows, it may become an issue for you or your web users.
*FUTURE OPPORTUNITIES:
* -This functions only return type and label properties. If you want to use pattern, id or p (for styling) you can add a check when looping through the columns
* and try to detect a particular column name that you define as the property (EG. if oci_field_name($stid, $i)=="GOOGLE_P_DATA" then ....)
*/
function getSQLDataTable($un,$pw,$db,$SQLString){
$conn=oci_connect($un,$pw,$db);
$stid= oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
oci_execute($stid);
$stid= oci_parse($conn, $SQLString);
oci_execute($stid);
$ncols = oci_num_fields($stid);
$cols = array();
$rows = array();
$cell = array();
for ($i = 1; $i <= $ncols; $i++) {
$column_label = '"'.oci_field_name($stid, $i).'"';
$column_type = oci_field_type($stid, $i);
switch($column_type) {
case 'CHAR': case 'VARCHAR2':
$column_type='"string"';
break;
case 'DATE':
$column_type='"datetime"';
break;
case 'NUMBER':
$column_type='"number"';
break;
}
$cols[$i-1]=array('"type"'=>$column_type,'"label"'=>$column_label);
}
$j=0;
while (($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) != false) {
for ($i = 0; $i <= $ncols-1; $i++) {
switch(oci_field_type($stid, $i+1)) {
case 'CHAR': case 'VARCHAR2':
$cellValue='"'.$row[$i].'"';
$cellFormat='"'.$row[$i].'"';
break;
case 'DATE':
if($row[$i]==null){
$cellValue='""';
$cellFormat='""';
} else {
$cellValue=convertGoogleDate(date_create($row[$i]));
$cellFormat='"'.date_format(date_create($row[$i]), 'd/m/Y H:i:s').'"';
}
break;
case 'NUMBER':
$cellValue=number_format($row[$i], 2, '.', '');
$cellFormat='"'.$row[$i].'"';
break;
} //end of switch
$cell[$i]=array('"v"'=>$cellValue,'"f"'=>$cellFormat);
}
$rows[$j]=$cell;
$j++;
}
arrayToGoogleDataTable($cols, $rows);
}
/*This function takes in the columns and rows created in the previous function and returns the JSON String*/
function arrayToGoogleDataTable($cols, $rows) {
//Convert column array into google string literal
echo "{\n";
echo "\t".'"cols"'.": [\n";
for($i = 0; $i < count($cols)-1; $i++) {
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},\n";
}
//Last column without ending comma (},)
echo "\t\t{";
$n=count($cols[$i]);
foreach($cols[$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}\n\t]";
//Now do the rows
//Check if empty first
if (count($rows)>0){
echo ",\n\t".'"rows"'.": [\n";
//For each row
for($j = 0; $j < count($rows)-1; $j++) {
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
//Last column without ending comma (},)
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]},\n";
}
//Last row
echo "\t\t{".'"c":[';
//For each cell
for($i = 0; $i < count($rows[$j])-1; $i++) {
echo "{";
$n=count($rows[$j][$i]);
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "},";
}
$n=count($rows[$j][$i]);
echo "{";
foreach($rows[$j][$i] as $arrayKey => $arrayValue) {
echo $arrayKey . ":" . $arrayValue;
$n--;
if ($n>0) {echo ",";}
}
echo "}]}\n";
echo "\t]";
}
echo"\n}";
}
/*This simply takes in a Date and converts it to a string that the google API recognizes as a Date*/
function convertGoogleDate(DateTime $inDate) {
$googleString='"Date(';
$googleString=$googleString.date_format($inDate, 'Y').',';
$googleString=$googleString.(date_format($inDate, 'm')-1).',';
$googleString=$googleString.(date_format($inDate, 'd')*1).',';
$googleString=$googleString.(date_format($inDate, 'H')*1).',';
$googleString=$googleString.(date_format($inDate, 'i')*1).',';
$googleString=$googleString.(date_format($inDate, 's')*1).')"';
return $googleString;
}
?>
For the rest of the implementation on Java and HTML check the git repo posted above
I know its a late reply, but still a top hit on Google and I have been asked the question a couple of times

Related

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

How to display text when RSS feed is empty

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.

Error In Javascript code with php

I wanna make statistics in my website for the last 3 years
I want to show result like this
2016 : 159
2015 : 132
2014 : 200
I try my code (this's)
$date2 = date('Y');
$n = $date2;
for($i=$n-2;$i<=$n;$i++) {
$sql = "SELECT sum(count) AS value_sum FROM statistics where YEAR(st_date) = $i ";
$sql_sel = mysqli_query($conn,$sql);
echo '
<script>
var pieData = [
';
while($rows = mysqli_fetch_assoc($sql_sel)) {
if($i == $n-2) {
echo '{
value: '.$rows['value_sum'].',
color:"#337AB7"
},';
}
else if($i == $n-1) {
echo '{
value: '.$rows['value_sum'].',
color:"#FC8213"
},';
}
else if($i == $n) {
echo '{
value: '.$rows['value_sum'].',
color:"#8BC34A"
},';
}
echo'];
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>';
}}
?>
but this code give me just 1 one row like this
2016 : 159
I wanna see all result, any help ?
You're creating 3 charts within your for loop. If you allow php to encode the data for you, you can echo the script outside of the PHP like so:
$date2 = date('Y');
$n = $date2;
$data = array();
for($i=$n-2;$i<=$n;$i++) {
$sql = "SELECT sum(count) AS value_sum FROM statistics where YEAR(st_date) = $i ";
$sql_sel = mysqli_query($conn,$sql);
while($rows = mysqli_fetch_assoc($sql_sel)) {
if($i == $n-2) {
$data[] = array('value'=> $rows['value_sum'], 'color'=>'#337AB7');
}
else if($i == $n-1) {
$data[] = array('value'=> $rows['value_sum'], 'color'=>'#FC8213');
}
else if($i == $n) {
$data[] = array('value'=> $rows['value_sum'], 'color'=>'#8BC34A');
}
}
}
?>
<script>
var pieData = <?php json_encode($data) ?>;
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>
This should help you out:
<?php
// Store the array for the pie data within PHP at first
$js_pie_data = [];
// Define colors
$colors = [
date('Y') => '8BC34A', // current year
(date('Y') - 1) => 'FC8213', // last year
(date('Y') - 2) => '337AB7' // 2 years ago
];
$sql = "SELECT
YEAR(st_date) as `year`, -- get year from DB, makes life simpler :)
sum(count) AS value_sum
FROM
statistics
WHERE
YEAR(st_date) >= (YEAR(CURDATE())-2) -- get all records from 2 years ago to today
GROUP BY
YEAR(st_date) -- group by year so that our sum() above will work";
$sql_sel = mysqli_query($conn,$sql);
while($rows = mysqli_fetch_assoc($sql_sel))
{
// keep adding entries to the pie data
$js_pie_data[] = [
'value' => $rows['value_sum'],
'color' => '#'.$colors[$rows['year']] // based on year from DB, pick a color
];
}
echo '<script>
var pieData = '.json_encode($js_pie_data).'; // this will output a properly formatted JS array which will be understood by JS with no problem
new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData);
</script>';
1)You can create array in php side.
2)Then convert it as json string.
3)Define javascript variable with that json string
4)Convert it as object with JSON.parse
5)Insert it in option
<?php
$db = Array("1","2","3");
$out = Array();
$x = 0;
foreach($db as $vals){
if($x == 1){
$out[] = Array("value"=>$vals,"color"=>"#bfbfbf");
}
if($x == 2){
$out[] = Array("value"=>$vals,"color"=>"#00ffff");
}
if($x == 3){
$out[] = Array("value"=>$vals,"color"=>"#fff00");
}
if($x == 3){$x = 0;}
$x++;
}
echo "
<script language='javascript'>
var stat_str = '".json_encode($out)."';
var stat_obj = JSON.parse(stat_str);
// then you can insert stat_obj if you need object into stats
</script>";
?>

Alert box is not showing in codeigniter models

in the model alert is not working. if condition is working,the only problem with the alert box, its not showing the dialog box.Please help..
public function setJumlahPenumpang ($idJadwal,$idPemesanan,$jml,$booked,$selected){
$data1 = $this->db->query('select p.jumlah_kursi, j.jumlah_penumpang, p.harga from tb_po p JOIN tb_jadwal j ON j.id_po = p.id_bus WHERE j.id_jadwal ='. $idJadwal);
foreach ($data1->result_array() as $dataa1) {
$tersedia = $dataa1['jumlah_kursi'] - $dataa1['jumlah_penumpang'];
if($tersedia < $jml){
?>
<script type="text/javascript">
document.location = '<?php echo base_url(); ?>proses/cekKode1/<?php echo $idPemesanan ?>';
alert("Tidak ada Bus Beroperasi");
</script>
<?php
}else{
$data3 = $dataa1['harga'] * $jml;
$this->db->query('update tb_pemesanan set harga = '.$data3.' where id_pemesanan = '.$idPemesanan);
$data = $this->db->query('select jumlah_penumpang from tb_jadwal where id_jadwal ='. $idJadwal);
$this->db->query("update tb_jadwal set booked = '".$booked."' where id_jadwal = ".$idJadwal);
$this->db->query("update tb_pemesanan set kursi = '".$selected."' where id_pemesanan = ".$idPemesanan);
foreach ($data->result_array() as $dataa) {
$data2 = $dataa['jumlah_penumpang'] + $jml;
$this->db->query('update tb_jadwal set jumlah_penumpang = '.$data2.' where id_jadwal = '.$idJadwal);
}
}
}
}
Try Echo Before Script Tag I hope So it 'll work....
if($package_id == NULL) {
echo '<script type="text/javascript">
window.location.href = "'.base_url().'"
</script>';
return;
die();
}

See Events in calendar, using PHP and Javascript,

In this matter, I have a problem when site is online(live), it works very good locally but when online (live) does not show events
<script type="text/JavaScript" language="JavaScript">
events = new Array(
<? php
$get_event = $db - > Execute("SELECT * FROM events WHERE fromdate>= date(now()) and removed='N'");
// $get_event=$db->Execute("SELECT * FROM events WHERE fromdate>='".$_SESSION['session_start_date_s_front']."' and removed='N'");
$ttl_event = $get_event - > RecordCount();
$gp = 1;
while (!$get_event - > EOF) {
$xx = dates_range($get_event - > fields['fromdate'], $get_event - > fields['todate']);
$ttl_dte = count($xx) - 1;
for ($i = 0; $i < count($xx); $i++) {
$d_e = explode('-', $xx[$i]);
if ($gp == $ttl_event && $i == $ttl_dte) { ?> ["D", "<?php echo $d_e[1]?>", "<?php echo $d_e[2]?>", "<?php echo $d_e[0]?>", "1:00 AM", "12:59 PM", "<?php echo addslashes($get_event->fields['event'])?>", ""] <? php
} else { ?> ["D", "<?php echo $d_e[1]?>", "<?php echo $d_e[2]?>", "<?php echo $d_e[0]?>", "1:00 AM", "12:59 PM", "<?php echo addslashes($get_event->fields['event'])?>", ""], <? php
}
}
$gp++;
$get_event - > MoveNext();
}
?>
Create a Database Table
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Block',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*
* Function requested by Ajax
*/
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'getCalender':
getCalender($_POST['year'],$_POST['month']);
break;
case 'getEvents':
getEvents($_POST['date']);
break;
default:
break;
}
}
/*
* Get calendar full HTML
*/
function getCalender($year = '',$month = '')
{
$dateYear = ($year != '')?$year:date("Y");
$dateMonth = ($month != '')?$month:date("m");
$date = $dateYear.'-'.$dateMonth.'-01';
$currentMonthFirstDay = date("N",strtotime($date));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>
<div id="calender_section">
<h2>
<<
<select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>
>>
</h2>
<div id="event_list" class="none"></div>
<div id="calender_section_top">
<ul>
<li>Sun</li>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
$dayCount = 1;
for($cb=1;$cb<=$boxDisplay;$cb++){
if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){
//Current date
$currentDate = $dateYear.'-'.$dateMonth.'-'.$dayCount;
$eventNum = 0;
//Include db configuration file
include 'dbConfig.php';
//Get number of events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$currentDate."' AND status = 1");
$eventNum = $result->num_rows;
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
}
//Date cell
echo '<span>';
echo $dayCount;
echo '</span>';
//Hover event popup
echo '<div id="date_popup_'.$currentDate.'" class="date_popup_wrap none">';
echo '<div class="date_window">';
echo '<div class="popup_event">Events ('.$eventNum.')</div>';
echo ($eventNum > 0)?'view events':'';
echo '</div></div>';
echo '</li>';
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<script type="text/javascript">
function getCalendar(target_div,year,month){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getCalender&year='+year+'&month='+month,
success:function(html){
$('#'+target_div).html(html);
}
});
}
function getEvents(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getEvents&date='+date,
success:function(html){
$('#event_list').html(html);
$('#event_list').slideDown('slow');
}
});
}
function addEvent(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=addEvent&date='+date,
success:function(html){
$('#event_list').html(html);
$('#event_list').slideDown('slow');
}
});
}
$(document).ready(function(){
$('.date_cell').mouseenter(function(){
date = $(this).attr('date');
$(".date_popup_wrap").fadeOut();
$("#date_popup_"+date).fadeIn();
});
$('.date_cell').mouseleave(function(){
$(".date_popup_wrap").fadeOut();
});
$('.month_dropdown').on('change',function(){
getCalendar('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val());
});
$('.year_dropdown').on('change',function(){
getCalendar('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val());
});
$(document).click(function(){
$('#event_list').slideUp('slow');
});
});
</script>
<?php
}
/*
* Get months options list.
*/
function getAllMonths($selected = ''){
$options = '';
for($i=1;$i<=12;$i++)
{
$value = ($i < 10)?'0'.$i:$i;
$selectedOpt = ($value == $selected)?'selected':'';
$options .= '<option value="'.$value.'" '.$selectedOpt.' >'.date("F", mktime(0, 0, 0, $i+1, 0, 0)).'</option>';
}
return $options;
}
/*
* Get years options list.
*/
function getYearList($selected = ''){
$options = '';
for($i=2015;$i<=2025;$i++)
{
$selectedOpt = ($i == $selected)?'selected':'';
$options .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>';
}
return $options;
}
/*
* Get events by date
*/
function getEvents($date = ''){
//Include db configuration file
include 'dbConfig.php';
$eventListHTML = '';
$date = $date?$date:date("Y-m-d");
//Get events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1");
if($result->num_rows > 0){
$eventListHTML = '<h2>Events on '.date("l, d M Y",strtotime($date)).'</h2>';
$eventListHTML .= '<ul>';
while($row = $result->fetch_assoc()){
$eventListHTML .= '<li>'.$row['title'].'</li>';
}
$eventListHTML .= '</ul>';
}
echo $eventListHTML;
}
?>
//In index.php
<?php
//Include the event calendar functions file
include_once('functions.php');
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Event Calendar by CodexWorld</title>
<!-- Include the stylesheet -->
<link type="text/css" rel="stylesheet" href="style.css"/>
<!-- Include the jQuery library -->
<script src="jquery.min.js"></script>
</head>
<body>
<!-- Display event calendar -->
<div id="calendar_div">
<?php echo getCalender(); ?>
</div>
</body>
</html>

Categories