i am not getting pie chart using codeigniter - ajax

I want a pie chart of expenses in percentage,my code is below, when i run the code it is not displaying nothing.please help.if possible please correct the code. i am really confused,only blank page is coming.
my controller chart
class Chart extends CI_Controller {
function chart() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('chart_m');
$this->load->library('session');
}
public function index()
{
$data['pie'] = json_encode($this->chart_m->selectexpenses());
$this->load->view('home',$data);
}
}
model chart_m
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Chart_m extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function selectexpenses()
{
$results = $this->db->query("SELECT expenses from myTable");
return $results->result_array();
}
}
my view page home.php
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<head><script>
$(document).ready(function () {
$(function () {
var chart;
// Build the chart
$('.widget-lower-left#widget').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'expenses'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'expenses',
data: []
}]
});
});
function requestData() {
$.ajax({
url:'<?php echo base_url().'index.php/chart'?>',
datatype: "json",
success: function(data) {
alert(data);
console.log(data);
var newData = [];
for( var i = 0, len = data.length; i < len; i++ ) {
var item = data[i];
for(var j in item){
newData.push([j,item[j]]);
}
}
chart.series[0].setData(newData);
</script>
},
cache: false
});
};
});
////////////////////////

May be You should Try This..
RewriteEngine on
RewriteCond $1 !^(index\.php|public|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
The controller is like
<?php
class Charts extends Controller {
public function __construct() {
parent::__construct();
$this->load->library('FusionCharts');
}
public function index() {
$this->load->view('charts_index');
}
public function getData($year='2010') {
// Instantiate the FusionCharts object
$FC = new FusionCharts();
// specify the graph parameters
$strParam="caption=Quarterly Sales for ".$year.";xAxisName=Quarter;yAxisName=Revenue;numberPrefix=$;decimalPrecision=0;formatNumberScale=1";
$FC->setChartParams($strParam);
// specify the data bsaed on the $year parameter
if ($year=='2010') {
$FC->addChartData("40800","name=Q1");
$FC->addChartData("31400","name=Q2");
$FC->addChartData("26700","name=Q3");
$FC->addChartData("54400","name=Q4");
} else {
$FC->addChartData("800","name=Q1");
$FC->addChartData("400","name=Q2");
$FC->addChartData("700","name=Q3");
$FC->addChartData("200","name=Q4");
}
// output the FusionCharts XML
print $FC->getXML();
}
}
?>
and the view is like this
<html>
<head>
<title>Dynamic Graphs with JQuery and FusionCharts</title>
<script language="JavaScript" src="/public/js/FusionCharts.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="JavaScript">
function drawChart(chartSWF, strXML, chartdiv) {
//Create another instance of the chart.
var chart = new FusionCharts(chartSWF, "chart1Id", "400", "300", "0", "0");
chart.setDataXML(strXML);
chart.render(chartdiv);
}
function updateChart() {
//call the CI data url
$.get('/charts/getData/'+$('#changeData').val(), function(data) {
if ($('#changeChart').val()==='3d') {
drawChart("/public/fscharts/FCF_Column3D.swf", data,"chart1div");
} else {
drawChart("/public/fscharts/FCF_Column2D.swf", data,"chart1div");
}
});
}
$(document).ready(function(){
//create the chart initially
$.get('/charts/getData/', function(data) {
drawChart("/public/fscharts/FCF_Column3D.swf", data, "chart1div");
});
//update the chart if the dropdown selection changes
$('#changeChart').change(function() {
updateChart();
});
$('#changeData').change(function() {
updateChart();
});
});
</script>
</head>
<body>
<select name="changeData" id="changeData">
<option value="2010" selected>2010</option>
<option value="2009">2009</option>
</select>
<select name="changeChart" id="changeChart">
<option value="3d">3D Version</option>
<option value="2d">2D Version</option>
</select><br>
<div id="chart1div" align="left">The chart will appear within this DIV. This text will be replaced by the chart.</div>
</body>
</html>
hope this will help you other wise visit this site...
Click ON this for More Help

Related

DataTable with .Net5

I tried to use datatable with my project and I always got undefined when data return from the controller while I checked the controller already returned 1000 records
this is my controller
[HttpGet]
public JsonResult get_Student_Info()
{
var model = (from C in _db1.ClassesInfos
select new Classes
{
ClassId = C.Id,
ClassCounty = C.ClassCounty ?? "",
ClassLocation = C.ClassLocation,
ClassSize = C.ClassSize ?? 0,
ClassDate = C.ClassDate.ToString(),
//ClassMonitorId = C.MonitorId,
//ClassActive = C.Active ?? 0,
//ClassLastModifedDate = C.LastModifiedDate.ToString(),
//ClassPasscode = C.Passcode,
//ClassType = C.ClassType
}).FirstOrDefault();
return Json(mymodel, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
and this is my view
$(function () {
$.ajax({
type: "GET",
//url: "/Instructor/get_Student_Info",
url: '#Url.Action("get_Student_Info", "Instructor")',
mimeType: 'json',
async: true,
success: function(data) {
$.each(data, function (i, data) {
alert(data.ClassCounty);
alert(data.ClassLocation);
var body = "<tr>";
body += "<td>" + data.ClassCounty + "</td>";
body += "<td>" + data.ClassLocation + "</td>";
body += "</tr>";
$( "#ClasssInfo tbody" ).append(body);
});
/*DataTables instantiation.*/
$( "#ClasssInfo" ).DataTable();
},
});
});
In asp.net mvc, it should be:
Model:
public class Class
{
public string ClassCounty { get; set; }
public string ClassLocation { get; set; }
}
View:
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'ClassCounty' },
{ 'data': 'ClassLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
//must be list model
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In asp.net core/.net 5, it should be:
View:
Note: In asp.net core/.net 5, the response json format is camel case.
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'classCounty' }, //difference here..should be camel case
{ 'data': 'classLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model);
}

Multi select with select2 and ajax laravel resource

For my series form, I need to have all the actors ready for a selection. I have a lot of actors and I need to get them with an api.
I made a Actor Resource :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ActorResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
// return parent::toArray($request);
return [
'id'=> $this->id,
'name'=> $this->name,
];
}
}
With routes :
Route::get('/actor', function () {
return ActorResource::collection(Actor::all());
});
Route::get('/actor/{actor}', function (Actor $actor) {
return new ActorResource($actor);
});
In my blade :
<label for="creators" class="label">Créateur</label>
<select class="form-control tags-selector" id="creators" name="creators[]" multiple="multiple">
</select>
<script>
$(document).ready(function() {
$('.tags-selector').select2({
minimumInputLength: 2,
ajax: {
url: '/api/actor',
dataType: 'json',
delay: 250,
},
});
});
</script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
Nothing is working... And how can I get the selected value after ?
Is this the right way to do a multi select with a big table ?
$(document).ready(function() {
$('.tags-selector').select2({
minimumInputLength: 2,
$.ajax: {
method:'get'// I am assuming this is a get method
url: '/api/actor',
dataType: 'json',
delay: 250,
success: function (data) {
console.log(data)//after you see the structure of data, try smt like
//this. You should change this part acording yo your data
for(int i =0;i<data.data.lenght;i++){
$("#creators").append(new Option(data.data[i].name, data.data[i].id));
}
},
error: function (error) {
console.log(error);
},
},
});
});
Well,I hope that will help you. I am also not the expert of them. Let me know if its works or not
Update
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="box" onkeydown="asd()" />
<select name="asd" id="select_box">
</select>
<script>
function asd() {
var data = {"data":[{"id":50,"name":"Alec"},{"id":51,"name":"Recep"},{"id":52,"name":"Aecep"}]};
$("#box").on("keyup", function(){
$('#select_box').empty();
var search_text = $("#box").val().toLowerCase();
data_value = data.data[0].name.substring(search_text.length).toLowerCase();
for (var i=0; i<data.data.length; i++) {
if(search_text === data.data[i].name.substring(0,search_text.length).toLowerCase()){
$("#select_box").append(new Option(data.data[i].name, data.data[i].id));
}
}
});
}
</script>
</body>
</html>
This code is working. Change the variables properly for your project

i have an error when use chart on laravel

Can someone can help me? I get an error when I try to use a chart.
Undefined variable: label (View: C:\xampp\htdocs\latihan_penjualan\resources\views\home.blade.php)
in 15bd1eeee4b4d1b903b52322d785ce7ce1ab31d2.php line 31
This is my controller:
public function index()
{
$kategori = DB::table('kategoris')->get();
$data = [];
$label = [];
foreach ($kategori as $i => $v) {
$value[$i] = DB::table('produks')->where('id_kategori',$v->id)->count();
$label[$i] = $v->nama;
}
return view('home');
$this->with('value',json_encode($value));
$this->with('label',json_encode($label));
}
And this is my view:
<div id="container" style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script type="text/javascript" src="http://www.chartjs.org/dist/2.7.2/Chart.bundle.js"></script>
<script type="text/javascript" src="http://www.chartjs.org/samples/latest/utils.js"></script>
<script type="text/javascript">
var color = Chart.helpers.color;
var barChartData = {labels: {!! $label !!},
datasets: [{
label: 'Produk Per Kategori',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: {!! $value !!},
}],
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Grafik Data Produk'
}
}
});
};
</script>
I already declared the variable $label.
Thanks in advance.
return view('home')
->with(['value'=>json_encode($value),'label'=>json_encode($label)]);
Fix this part after return view('home');
public function index()
{
$kategori = DB::table('kategoris')->get();
$data = [];
$label = [];
foreach ($kategori as $i => $v) {
$value[$i] = DB::table('produks')->where('id_kategori',$v->id)->count();
$label[$i] = $v->nama;
}
return view('home')->with('value',json_encode($value))->with('label',json_encode($label));
}

How to insert infinite scroll to Laravel Project

Am very new to Jquery and Ajax being used in laravel and been trying to implement infinite scroll to my project and i have no idea where to start
The Controller:
$books= DB::table('books')->where('status', 'post')->orderBy('created_at', 'DESC')->paginate(15);
if ($books->isEmpty())
{
$books= null;
return view('landingpage')->withBooks($books);
}
return view('landingpage')->withBooks($books);
The view
#if ($books== null)
<center><p class="paragraph"> Be the first to share your shopping experience here</p></center>
#else
<div class="row mt-0"> <div class="infinite-scroll"> #foreach ($books as $item)
<div class="col-lg-4 mt-3">
<p class="paragraph"> <sup><i class="fa fa-quote-left" style="font-size:5px" aria-hidden="true"></i></sup>{{$item->title}}<sup><i class="fa fa-quote-right" style="font-size:5px" aria-hidden="true"></i></sup> </p>
<img src="../images/{{$item->rate}}.png" style="width:50%" alt="Image">
<h2 style="font-size:18px">{{$item->firstname}} {{$item->lastname}}</h2> </div>#endforeach </div>{{$books->links()}}</div>
#endif
The JS
<script type="text/javascript">
$('ul.pagination').hide();
$(function() {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="images/loading.gif" alt="Loading..." />',
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('ul.pagination').remove();
}
});
});
Any help will be grately appreciated
I use ajax for infinate scroll this is example :
Method for view :
public function index(){
return view('index');
}
Method for get data wia ajax:
public function ajaxData(Request $request)
{
$post_query = Trends::query()
->where('is_offer', '!=', 1)
->where('direct_to', null)
->orderBy('id', 'desc')
->paginate(12);
$data['post_list'] = $post_query;
if ($data['post_list']->count() > 0) {
$ajax_data['post'] = true;
$ajax_data['next_url'] = $data['post_list']->nextPageUrl();
$ajax_data['next_data'] = $data['post_list'];
} else {
$ajax_data['html'] = false;
$ajax_data['post'] = false;
$ajax_data['next_url'] = $data['post_list']->nextPageUrl();
}
return response()->json($ajax_data);
}
And this is my script in blade
var loaddataUrl = '{!! route('explore-ajax-data',array_merge(request()->all())) !!}';
var nextData = true;
$(document.body).on('touchmove', onExploreScroll); // for mobile
$(window).on('scroll', onExploreScroll);
function onExploreScroll() {
if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.9) {
if (nextData) {
nextData = false;
loadMoreData();
}
}
}
function loadMoreData() {
$.ajax({
type: 'GET',
url: loaddataUrl,
success: function (data) {
if (data.next_url) {
loaddataUrl = data.next_url;
console.log(data.next_data);
nextData = true;
} else {
nextData = false;
}
},
error: function (data) {
nextData = true;
}
})
}
route(explore-ajax-data) map to public function ajaxData(Request $request)
my routes are :
// this will display home page or home view
Route::get('home', 'HomeController#index')->name('home');
// this is for ajax request.
Route::get('ajax/explore-data', 'HomeController#ajaxData')->name('explore-ajax-data');
link of tutorial

JQuery autocomplete function not loading

I'm working on autocomplete JQuery function to populate student names in the text box. I've utilized every related JQuery library to make the autocomplete function work. When i press F12, it always throws an error which is "autocomplete is not a function". Below is my code that I'm running.
StudentBatch.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
alert("This is autocomplete function");
});
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response) {
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
try {
response($.map(data, function (item) {
return { label: item.StudentName, value: item.StudentName };
}))
} catch (err) { }
}
})
},
messages: {
noResults: "jhh", results: "jhjh"
}
});
});
</script>
StudentController.cs
[HttpPost]
public JsonResult Create(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "fae30ef0-08b2-4490-a389-3c8eb0a7cc53";
var StudentList = user.GetAllUsers().ToList().Where(u => u.FirstName == Prefix && u.usertypeid == stdid).ToString();
return Json(StudentList, JsonRequestBehavior.AllowGet);
}
I have created similar demo which you are creating.
Model
public class CreateUser
{
public string StudentName { get; set; }
public string StudentId { get; set; }
}
Controller
public class StudentController : Controller
{
// GET: Student
public ActionResult Create()
{
return View();
}
[HttpPost]
public JsonResult Create(string prefix)
{
List<CreateUser> studentList = new List<Models.CreateUser>()
{
new CreateUser { StudentId = "1" , StudentName = "Student1"},
new CreateUser { StudentId = "2" , StudentName = "Student2"},
new CreateUser { StudentId = "3" , StudentName = "Student3"},
new CreateUser { StudentId = "4" , StudentName = "Student4"},
new CreateUser { StudentId = "5" , StudentName = "Student5"},
new CreateUser { StudentId = "6" , StudentName = "Student6"},
new CreateUser { StudentId = "7" , StudentName = "Student7"},
};
var searchlist = (from student in studentList
where student.StudentName.Contains(prefix)
select student).ToList();
return Json(searchlist, JsonRequestBehavior.AllowGet);
}
}
View
#model WebApplication6.Models.CreateUser
#{
Layout = null;
}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
.ui-autocomplete-input {
width: 300px;
}
</style>
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.StudentName, value: item.StudentName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
Output

Resources