Uncaught ReferenceError: year is not defined in google chart using ajax/codeigniter - ajax

Good day. I want to make my column char working with database but I got this error says "Uncaught ReferenceError: year is not defined". here is my code.
JAVASCRIPT
function year()
{
var e = document.getElementById("selectyear");
var year = e.options[e.selectedIndex].text;
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('chartcontroller/chart/')?>/" + year,
type: "GET",
dataType: "JSON",
success: function(data)
{
drawChart1(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1(data) {
var data = google.visualization.arrayToDataTable([
['Courses', 'S.Y. 2011-2012', 'S.Y. 2012-2013','S.Y. 2013-2014'],
for(var i = 1; i < data.length; i++) {
comment = data[i];
[comment.Course, comment.year_a, comment.year_b, comment.year_c],
}
]);
var options = {
title: 'ColumnChart',
hAxis: {title: 'Courses', titleTextStyle: {color: 'blue'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
//ajax end
and my view html
<div class="grid text-center" style="display: block;">
<h1 style=" color: black; font-size: 18px;">Summary of Daily Utilization of Library Holdings per Department</h1>
<div class="input-group">
<span class="input-group-addon">#</span>
<select id="selectyear" class="form-control selectyear" data-mobile="true" name="year" onchange="year();">
<?php
for ($i=$min_year; $i <= $max_year; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
</div>
<h1 style=" color: gray; font-size: 14px;">S. Y. 2011-2012, 2012-2013 & 2013-2014</h1>
<div id="chart_div1" class="chart" style="height: 400px; width: 100%;"></div>
<div id="chart_div2" class="chart" style="height: 400px; width: 100%;"></div>
in my controller
public function chart($year)
{
$data = $this->views->chart($year);
//Either you can print value or you can send value to database
echo json_encode($data);
}
no problem with ajax because when I do a debugging ajax successfully retrieve the value from database, the problem is when I put that value to my column chart like what I did in my code I've got that error.. help me please. this is the last problem I have to my thesis project.. thanks. I want to change the column chart value if the drop down has change.

Related

Solve for the total every transaction is going in. (Google chart)

I have a chart where I need to calculate the amount I'm earning as time goes by. In this chart, I have the amount (red line). My target is to calculate the total of every transaction that is going in. My current code is not working properly because when the time is 18:26:23 it is 1000 amount when it is 18:26:24, it is still 1000... It should be 2000. It should solve for the sum over time. I have provided my codes below and a screenshot of my current system and my target. Thank you in advance.
Views:
<div class="col-md-12">
<!-- LINE CHART -->
<div class="card card">
<div class="card-header">
<h3 class="card-title">Stats Per Day</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" style="width:30%;">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="chart">
<div id="wholechart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></div>
</div>
</div>
<!-- /.card-body -->
</div>
</div>
Ajax:
function sampleeesasw(){
$.ajax({
type: 'post',
url: '<?=site_url('report/datas')?>',
dataType:'json',
success: function(result) {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function(){drawChart(result);});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'req');
data.addColumn('number', 'total');
data.addColumn('number', 'amount');
var dataArray =[];
$.each(result,function(i,obj){
dataArray.push([obj.req,parseInt(obj.total),parseInt(obj.amount)]);
});
data.addRows(dataArray );
var options = {
seriesType: "line",
};
var chart = new google.visualization.ComboChart(document.getElementById('wholechart')).
// Line,Bar,Area,Clomun,pie
draw(data, {curveType: "function",
vAxes: {0: {logScale: false},
1: {logScale: false, maxValue: 2}},
series:{
0:{targetAxisIndex:0},
1:{targetAxisIndex:1},
2:{targetAxisIndex:1}}}
);
}
}
});
}
setInterval(function(){
sampleeesasw()
},1000);
Controller:
public function datas(){
$data= $this->reports->wholedatachart();
foreach($data as $row){
$data['req']=$row['req'];
$data['amount']=$row['amount'];
$data['total']=$row['total'];
}
echo json_encode($data);
}
Model:
function wholedatachart(){
$query=$this->db->query("SELECT timeProcess as 'req', transID as 'total', amount as 'amount' FROM tbl_transaction");
return $query->result_array();
}
You can do calculation part inside your drawChart function. Inside that function you can simply total value of amount then , save it in some variable and pass it to your dataArray.push(..).
Demo Code :
//suppose data look like this..
var result = [{
"req": "1",
"amount": 2000,
"total": 1000
},{
"req": "2",
"amount": 1000,
"total": 1000
},{
"req": "3",
"amount": 1000,
"total": 1000
}]
function sampleeesasw() {
/*$.ajax({
type: 'post',
url: '',
dataType: 'json',
success: function(result) {*/
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(function() {
drawChart(result);
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'req');
data.addColumn('number', 'total');
data.addColumn('number', 'amount');
var dataArray = [];
var total=0 //intialze..
$.each(result, function(i, obj) {
total +=parseInt(obj.amount)//add on each iteration
dataArray.push([obj.req, parseInt(obj.total), parseInt(total)]); //add value here ..
});
data.addRows(dataArray);
var options = {
seriesType: "line",
};
var chart = new google.visualization.ComboChart(document.getElementById('wholechart')).draw(data, {
curveType: "function",
vAxes: {
0: {
logScale: false
},
1: {
logScale: false,
maxValue: 2
}
},
series: {
0: {
targetAxisIndex: 0
},
1: {
targetAxisIndex: 1
},
2: {
targetAxisIndex: 1
}
}
});
}
/* }
});*/
}
setInterval(function() {
sampleeesasw()
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div class="col-md-12">
<!-- LINE CHART -->
<div class="card card">
<div class="card-header">
<h3 class="card-title">Stats Per Day</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" style="width:30%;">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="chart">
<div id="wholechart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></div>
</div>
</div>
<!-- /.card-body -->
</div>
</div>
I think you can try this one, you need to increment the amount of each data, you can use a temporary variable and increment all the amount.
I edited the answer sorry my bad.
change your controller to
public function datas(){
$data= $this->reports->wholedatachart();
$tempAmount = 0;
foreach($data as $row){
$tempAmount = $tempAmount + $row['amount'];
$output[]=array(
'req' => $timeline['time'],
'amount' => $tempAmount,
'amount' => $row['amount'],
);
}
echo json_encode($output);
}
if you want to add the total also you can do the same thing

Google chart does not redraw the chart based on a new Ajax filter

How can I make this code update the google chart with new Ajax call data? When I submit from the dropdown list I see the updated data in the echoed results but the chart does not update. It seems like I have place the submit code in the wrong place.
<title>Google Chart in PHP and MySQL</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var drawChart;
$(document).ready(function () {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
$(".submit").click(function() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.Gender, parseInt(obj.HowMany)]);
});
data.addRows(dataArray);
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});
</script>
</head>
<body>
<center>
<img src="logo.png" style="width:200px;height:60px;">
</center>
<hr style="border: 4px solid blue;" />
<table class="columns" style="width:120%">
<tr>
<td>
<label>Gender filter</label>
<?php
//Connect to our MySQL database using the PDO extension.
$pdo = new PDO('mysql:host=localhost;dbname=panel', 'root', '');
//Our select statement. This will retrieve the data that we want.
$sql = "SELECT DISTINCT Gender FROM employee GROUP BY Gender";
//Prepare the select statement.
$stmt = $pdo->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$Ngender = $stmt->fetchAll();
?>
<!--Start here -->
<form method="post" action="indexdash2.php">
<select name="filter">
<option value="" disabled selected hidden>Choose a filter</option>
<?php foreach($Ngender as $Ngender): ?>
<option value="<?= $Ngender['Gender']; ?>"><?= $Ngender['Gender']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Find">
</form>
</td>
</table>
<hr style="border: 4px solid blue;" />
<h2>DEMOGRAPHICS</h2>
<table class="columns">
<tr>
<td>
<div id="piechart_div" style="border: 1px solid #ccc"></div>
</td>
</tr>
</table>
</body>
</html>
Any help will be appreciated! I am pretty sure I have missed something basic as I am new to this.
first, google's load method only needs to be called once per page load.
afterwards, you can draw the chart, or charts, as many times as needed.
next, google's load method will also wait on the page to load by default.
so we can use load in place of jquery's ready method.
recommend loading google first,
then make the call to get the data and draw the chart.
see following snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
function getData() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON"
}).done(function (result) {
drawChart(result);
});
}
$('.submit').click(getData);
getData();
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
$.each(result, function (i, obj) {
data.addRow([obj.Gender, parseInt(obj.HowMany)]);
});
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});

Laravel Ajax working fine on page reload but when I use Ajax to filter data pagination with jsscroll does not work

Pagination links working fine as normal pages when I refresh the whole page but when i reload just data with ajax pagination does not loading next pages
$.ajax({
url: '{{route('apply.filters')}}',
type:'get',
data: {cities:cities,
category:category
},
success: function (data) {
// $(".contentlist").load(location.href + " .contentlist");
$('.contentlist').html(data);
},
error: function(xhr, status, errorThrown) {
console.log(xhr.responseText);
}
});
this is my controller function
public function filter(Request $request)
{
try {
set_time_limit(390);
$country=null;
if(Auth::check() && $country==null){
$country=Auth::user()->lat->country??'';
}if(Session::has('country') && $country==null){
$country=Session::get('country.0');
}
if(isset($request->cities)){
$data =[
'products' => Product::where([['category',$request->category],['country',$country??'']])->whereIn('city',$request->cities)->where('status',1)->Orderby('id','desc')->paginate(8),
];
}
if(isset($data)){
return response()->json(view('front.home.ajaxindex',$data)->render());
}else{
return redirect()->route('home');
}
} catch(\Exception $e) {
return back()->with('error',$e->getMessage());
}
}
this is my jsscroll function working normally fine but not loading data comes with ajax
$('ul.pagination').hide();
$(function() {
$('.contentlist').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="{{asset('front_assets/images/Spinner-1s-200px.gif')}}" width="100" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.contentlist',
loadOnScroll: false,
callback: function() {
$('ul.pagination').remove();
$('.elements').each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) {
maxHeight = thisH;
}
$(this).height(maxHeight);
});
}
});
});
this is my ajaxindex page this is new page only created for making html which is appended in the main page if data exists
#foreach($products as $product)
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 item-cell">
<div class="listingscontent elements">
#if(\Illuminate\Support\Facades\Auth::guard('admin')->check())
<i id="{{$imgs->id??''}}" onclick="deletes('{{$product->id}}',this)" class="fa fa-close fa-lg pull-right" style="margin-left: -20px; mix-blend-mode: hard-light; color: rgb(0, 255, 255); "></i>
<a style=" position: absolute;" class="pull-left" href="{{route('edit.add',['id' => preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","#","#"], '-',$product->title??'')).'-'.$product->id??''])}}"> <i class="fa fa-pencil-square-o fa-lg" style="mix-blend-mode: hard-light; color: rgb(0, 255, 255); "></i></a>
#endif
<a style="color: #ea1b25" href="{{route('details',['id' => preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","#","#"], '-',$product->title??'')).'-'.$product->id??''])}}">
#if(isset($product->atachedImage))
<img class="listings" src="{{asset($product->atachedImage->path.$product->atachedImage->name??'noimage.jpg')}}" title="{{$product->title??''}}_image" alt="">
#else
<img class="listings" src="{{asset('images/noimage.jpg')}}" title="{{$product->title??''}}_image">
#endif
<h5 class="text-capitalize title" title="{{$product->title??''}}">{{str_limit($product->title??'',19)}}</h5></a>
</div>
</div>
#endforeach
{{$products->appends(request()->except('page'))->links()??''}}

Laravel ajax respond appending to body but not to #results

I have problem with outputting results from search in a div with id 'results' if I append the results to body they show up but when I change it to #results it's never appearing.
Search box is in navigation in master.blade.php and every other page includes it.
master.blade.php
<form id="search_form" action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value);" placeholder="Search">
</div>
<div id="result">
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $business )
<tr>
<td>{{ $business->logo }}</td>
<td>{{ $business->name}}</td>
</tr>
#endforeach
#endif
</table>
</div>
</div>
</form>
Controller:
public function search($search_value) {
$search_text = $search_value;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
//$data = $data->toArray();
return view('master')->with('results',$data);
}
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#results').append(data);
},
error: function(data) {
$('body').html(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Route::
Route::post('/searching/{search}', 'SearchController#search');
If I actually look into ajax response, result is there:
<table style="width:100%">
<tr>
<td></td>
<td>dasd</td>
</tr>
</table>
But it never appears on the page! It does if the append is changed to body.
//edit
I have a loading gif which worked fine but now it never dissapears and each time it executed ajax, it doesn't want to dissapear too:
$(document).ajaxStart(function() { Pace.restart(); });
$(window).on('load', function () {
setTimeout(function(){
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
}); // set the time here
});
$(document).ready(function() {
setTimeout(function() {
$(".messages").fadeOut(5000);
});
setTimeout(function() {
$(".messages").fadeOut(5000);
});
});
css:
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0.5;
background-color: #6d6968;
background: url(../images/default.gif) center no-repeat #fff;
}
jQuery.ajaxSetup({
beforeSend: function (xhr, data) {
$('.se-pre-con').show();
},
complete: function ()
{
$('.se-pre-con').hide();
}
});

Getting uploaded files count as zero while calling the function in controller through Json in mvc4

I created multiple file uploader dynamically using javascript within the div FileUploadContainer.while i put btnSubmit outside the form tag i get Request.Files.Count as zero.I need to call the PopUp() through Json .If i put btnSubmit inside the form tag
it does not call the Save() on javascript and will call PopUp() method on form submit.
I need to call the PopUp() through Json and need to get the Request.Files.Count .Pls help.
#using (Html.BeginForm("PopUp", "EnergyCatagory", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="FixedHeightContainer">
<div id="FileUploadContainer">
</div>
<input type="button" id="btnAddAttachment" name="btnAddAttachment" class="ZWidgetTitle"
value="Add More Attachments" onclick="AddFileUpload()" />
</div>
<div id="NewAttachment">
<div style="background-color: #DADADA;">
<center>
<label style="font-family: Verdana; font-size: 13px; font-weight: bold; color: black;
height: 30px; width: 100%; padding-top: 20px;" id="lblMessage">
</label>
</center>
</div>
</div>
<div class="horizSep">
</div>
<div id="buttons">
</div>
} <button id="btnSubmit" class="buttons" onclick="Save()">
Attach</button>
function Save()
{$.ajax({
url: '/EnergyCatagory/PopUp',
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("success");
}
});
}controller-----
public ActionResult PopUp()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
var path1 = Path.Combine(Server.MapPath("~/Files/"), FileName);
//PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
PostedFile.SaveAs(path1);
return Json(
new
{
CustomMessage = "My message",
});
}
}
If the form is getting submitted and don't calling the function onclick is because the input type is a button, you can change it to html a link tag.
also calling a inline javascript (onclick) is not good practice, i notice you use jquery so why don't do it with jquery?
function Save(){
$.ajax({
url: '/EnergyCatagory/PopUp',
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("success");
}
});
$("#btnSubmit").click(function(){
Save();
});
#using (Html.BeginForm("PopUp", "EnergyCatagory", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="FixedHeightContainer">
<div id="FileUploadContainer">
</div>
<input type="button" id="btnAddAttachment" name="btnAddAttachment" class="ZWidgetTitle"
value="Add More Attachments" onclick="AddFileUpload()" />
</div>
<div id="NewAttachment">
<div style="background-color: #DADADA;">
<center>
<label style="font-family: Verdana; font-size: 13px; font-weight: bold; color: black;
height: 30px; width: 100%; padding-top: 20px;" id="lblMessage">
</label>
</center>
</div>
</div>
<div class="horizSep">
</div>
<div id="buttons">
</div>
<a id="btnSubmit" class="buttons">Attach</a>
}
i think you are getting Request.Files.Count equals zero is because you don't have any input type file? do you?

Resources