Loading google datatable using ajax/json - ajax

I can't figure out how to load a datable using ajax/json. Here is my json code in a remote file (pie.json)
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
}
This is what I have tried so far but it doesn't work.
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["piechart"]});
function ajaxjson() {
jsonreq=GetXmlHttpObject();
jsonreq.open("GET", "pie.json", true);
jsonreq.onreadystatechange = jsonHandler;
jsonreq.send(null);
}
function jsonHandler() {
if (jsonreq.readyState == 4)
{
var res = jsonreq.responseText;
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(res, 0.6)
var chart = new google.visualization.PieChart(document.getElementByI('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
} // end drawChart
} // end if
} // end jsonHandler
function GetXmlHttpObject()
{
var xmlHttp=null;
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
Things work perfectly if I replace the 'res' variable with the actual code in pie.json.
Any help would be greatly appreciated.

Just a guess because I'm unfamiliar with the google objects you are using, but I'm pretty sure responseText just returns a string. JavaScript can't natively parse JSON (only XML to the best of my knowledge), so you'd have to eval("var res = " + jsonreq.responseText).
I hope this helps.

if I were in you, I'll use jQuery to save some code:
$.getJSON("pie.json", function(data) {
drawWanChart(data);
});
and here the function that draws your chart:
function drawWanChart(jsonData)
{
jsonData = jQuery.parseJSON(jsonData);
if(jsonData != null)
{
data = new google.visualization.DataTable(jsonData);
chart = new Google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data, null);
}
}
Please refer to official documentation:
$.getJSON
PieChart on Google Playground

Related

How to fetch data from DB on Chart.js using Laravel?

I want to show data from database on chart and I have shown return response I need to fetch on chart but I don't know how to do that does anyone have an idea?
Return response:
[
"Joylinkhk: 13,",
"HorizonTechnologies: 2,",
"Alahazrat: 9,",
"j2w: 0,"
]
Chart script:
<script>
var barChartData = {
labels: ['Joylinhk', 'HorizonTechnologies','Alahazrat','j2w'],
datasets: [{
label: "",
backgroundColor: window.chartColors.blue,
data: [13, 2,9,0],
}
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Project Report Chart'
}
,
tooltips: {
mode: 'index',
intersect: false
}
,
responsive: true,
scales: {
xAxes: [{
stacked: true,
}
],
yAxes: [{
stacked: true
}
]
}
}
}
);
};
</script>
I do This more than one time
first of all you should Include Google Chart in Your Blade File
Let's See The controller function that return data to the chart
I make a function called getAreaChart()
public function getAreaChart():array {
$data = DB::table('companies')->get();
$array[]=['area','counts'];
foreach ($data as $key=>$da):
$array[++$key] = [Area::find($da->area)->area,intVal($da->count)];
endforeach;
return $array;
}
for the function that return data to view and displayed in chart, I call the function and don't forget to json_encode the result
public function home()
{
$array = $this->getAreaChart();
return view('admin.home')->with('companies', json_encode($array));;
}
in the blade file , I make a div with id pie_chart
<div id="pie_chart" style="width:510px; height:408px;background: transparent">
and the script should be like this
<script type="text/javascript">
var analytics = <?php echo $companies; ?>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable(analytics);
var options = {
title : ''
};
var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
chart.draw(data, options);
}
</script>
You can change the chart by change the value corechart see google chart doc
this is example that I follow
Google Charts Docs
google.charts.load('current', {'packages':['corechart']});
and this is the google charts types
Google Charts Types
I hop that helpful ;)
happy code

Dropzone createThumbnailFromUrl() issue

I need to add pre-existing image files to dropzone by using Laravel 5.4. This is why I use createThumbnailFromUrl() function. But it does not generate images properly. Instead it shows them in blank way. I used that link (jsfiddle) for that purpose. I googled a lot, tried several ways, but it did not help:
Below is my code:
<script type="text/javascript" src='{{asset("js/dropzone/min/dropzone.min.js")}}'></script>
<script type="text/javascript">
Dropzone.options.addImages = {
paramName: "file", // The name that will be used to transfer the file
addRemoveLinks: true,
// The setting up of the dropzone
init:function() {
// Add server images
var myDropzone = this;
var existingFiles = [
{ name: "Filename 1.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 2.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 3.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 4.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 5.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' }
];
for (i = 0; i < existingFiles.length; i++) {
// alert(existingFiles[i].imageUrl);
myDropzone.emit("addedfile",existingFiles[i]);
myDropzone.files.push(existingFiles[i]);
myDropzone.createThumbnailFromUrl(existingFiles[i], existingFiles[i].imageUrl, function() {
myDropzone.emit("complete", existingFiles[i]);
}, "anonymous");
}
},
};
</script>
Here is the result :( :
P.S: Any kind of help would be appreciated.
had the same issue with dropzone 5.3
this fixed it for me
let mockFile = { name: "Loaded File", dataURL: relURL };
dropzoneInst.files.push(mockFile);
dropzoneInst.emit("addedfile", mockFile);
dropzoneInst.createThumbnailFromUrl(mockFile,
dropzoneInst.options.thumbnailWidth,
dropzoneInst.options.thumbnailHeight,
dropzoneInst.options.thumbnailMethod, true, function (thumbnail)
{
dropzoneInst.emit('thumbnail', mockFile, thumbnail);
});
dropzoneInst.emit('complete', mockFile);
I am attaching for reference my solution, based on many previous answers, but mostly on Raphael Eckmayer. This is how it is done to make it work well with Django 3.0.5 and dropzone.js 5.7.0. Maybe it is not the best solution, but it works.
I am sending my current images from Django view using new template tag json_script that packs my list of files prepared in Django into JSON. Basically in my template I have this:
{{ images|json_script:"images" }}
Then I process this in my script. Here is entire script from my site, hope that will help someone.
EDIT:
I had an issue with this code that if I add new pictures to the dropzone together with the old one from database I got this form submitted twice. In first pass I get pictures from dropzone.js, but also all fields since I am copying them from the form. And then, on second pass, I am submitting form again but now without pictures. My view actually was handling this well and storing data, but when I started to write down how to handle removed pictures on form edit I had issue with this, so I decided to handle this differently. Please note that code is now changed and instead of submitting form twice I am sending entire form and pictures with dropzone, but after successmultiple I am just redirecting to other page. Everything is updated and stored then. So the change is in the successmultiple part.
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Dropzone.autoDiscover = false;
var first_time = true;
var old_images = JSON.parse(document.getElementById('images').textContent)
var myDropzoneX = new Dropzone("div#mydropzone", {
autoProcessQueue: false,
url: "{% url 'site_report_edit' report_id=1 %}",
addRemoveLinks: true,
thumbnailWidth: 400,
thumbnailHeight: 400,
uploadMultiple: true,
parallelUploads: 12,
init: function() {
var myDropzone = this;
var addButton = document.getElementById("submit-btn");
if (old_images) {
console.log(old_images);
for (x in old_images) {
var mockFile = {
name: old_images[x].name,
size: old_images[x].size,
kind: 'image',
dataURL: old_images[x].urlich,
accepted: true
}
myDropzone.files.push(mockFile);
myDropzone.emit('addedfile', mockFile);
createThumbnail(mockFile);
console.log(old_images[x].name, old_images[x].urlich);
}
function createThumbnail(temp) {
myDropzone.createThumbnailFromUrl(temp,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod, true, function (thumbnail) {
myDropzone.emit('thumbnail', temp, thumbnail);
myDropzone.emit("complete", temp);
});
}
myDropzone._updateMaxFilesReachedClass();
}
addButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
document.getElementById("dropzone-form").submit();
}
});
this.on("successmultiple", function (files, response) {
setTimeout(function (){
{#document.getElementById("dropzone-form").submit();#}
window.location.href = "/admin/report/{{ report_id }}";
}, 1000);
});
},
sending: function (file, xhr, formData) {
var formEl = document.getElementById("dropzone-form");
if (first_time) {
for (var i=0; i<formEl.elements.length; i++){
formData.append(formEl.elements[i].name, formEl.elements[i].value)
first_time = false;
}
}
formData.append('csrfmiddlewaretoken', getCookie('csrftoken'));
formData.append("image", file.name);
}
});
</script>
Please note that there are some comments and some writing to console.log, but you can obviously get rid of this.
I had the same problem. Use these files:
https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.js
https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.css
It worked for me.
I know it's a bit late, however I was facing the same issue. The problem I was having was a race condition where only the last thumbnail was loaded and the others were stuck before completing, because i changed before createThumbnailFromUrl was getting it's data. Putting the call inside function did the trick for me:
for (var i = 0; i < images.length; i++) {
var temp = { name: images[i], dataURL: images[i] };
myDropzone.files.push(temp);
myDropzone.emit("addedfile", temp);
createThumbnail(temp);
}
function createThumbnail(temp) {
myDropzone.createThumbnailFromUrl(temp,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod, true, function (thumbnail) {
myDropzone.emit('thumbnail', temp, thumbnail);
myDropzone.emit("complete", temp);
});
}
My answer is inspired by BLitande's, which helped me getting it to kind of work in the first place.

JSON and HTML troubles

i'm currently having some troubles with displaying the information from a JSON file to html. I'm currently using AJAX to get the data from the JSON file.
The main problem that i'm facing is with displaying all the data into one div.
function Test(){
request.open('GET','/json/anime.json');
request.onreadystatechange = function() {
if((request.readyState===4) && (request.status===200)) {
var json = JSON.parse(request.responseText);
for(var title in json.Title ) {
for(var ep in json.Episode) {
for(var img in json.Image) {
for(var link in json.Link) {
_title = json.Image[title];
episode = json.Image[ep];
image = json.Image[img];
_link = json.Image[link];
var div = document.createElement('div');
div.className = 'card card-inverse';
div.innerHTML = `<img class="card-img img-fluid img-responsive" src="${image}" data-toggle="modal">`;
document.getElementById('anime').appendChild(div);
}
}
}
}
}
}
request.send();
}
The JSON file looks like this...
{
Episode: [
...
],
Image: [
...
],
Link: [
...
],
Title: [
...
]
}
The way above is working if i'm only looping over one of the four arrays, however crashes chrome when trying to do the above task.
Any help would be appreciated.
Thanks
I decided to take a different approach moving away from ajax a little and moving more towards jquery. Below is what has so far worked out for me. Thanks to the people who commented above, really helped me think of ways to tackling it.
function DisplayCards() {
var i = 0;
$.getJSON('/json/anime.json', function(data) {
$.each(data, function(index) {
for(key in data[index]){
e = data.Image.length;
console.log(e);
if(i < e)
{
image = data.Image[key];
link = data.Link[key];
console.log(i += 1);
var div = document.createElement('div');
div.className = 'card card-inverse';
div.innerHTML = `<img class="card-img img-fluid img-responsive" src="${image}" data-toggle="modal">`;
var p = document.createElement('p');
p.innerHTML = 'id="wrapper" class="text"';
document.getElementById('anime').appendChild(div);
}
}
console.log(data);
});
});
}

graphael charts with dynamic data from database using ASP.NET MVC3

I would like to understand how to get data from a database and show that data inside a graphael chart.
I'm working in ASP.NET MVC3 and I really don't understand how to make the things working.
Any help is really appreciated.
great I solved the problem!
I think that could be useful for someone else too:
here it is the Controller code:
public ActionResult ActionName()
{
List<String> data = new List<String>();
data.Add("legend0_4");
data.Add("legend1_5");
data.Add("legend2_8");
data.Add("legend3_12");
data.Add("legend4_8");
return Json(data, JsonRequestBehavior.AllowGet);
}
here it is the ajax side that also creates the pie chart:
jQuery.getJSON("/ControllerName/ActionName", function (data) {
// # Init
var levels = [], values = [];
for (var id in data) {
var compo = data[id].split("_");
levels.push("%%.%% " + compo[0]);
values.push(parseInt(compo[1]));
}
var r = Raphael("accountCharts"),
pie = r.piechart(320, 240, 100, values, { legend: levels, legendpos: "west", href: ["http://raphaeljs.com", "http://g.raphaeljs.com"] });
r.text(320, 100, "Interactive Pie Chart").attr({ font: "20px sans-serif" });
pie.hover(function () {
this.sector.stop();
this.sector.scale(1.1, 1.1, this.cx, this.cy);
if (this.label) {
this.label[0].stop();
this.label[0].attr({ r: 7.5 });
this.label[1].attr({ "font-weight": 800 });
}
}, function () {
this.sector.animate({ transform: 's1 1 ' + this.cx + ' ' + this.cy }, 500, "bounce");
if (this.label) {
this.label[0].animate({ r: 5 }, 500, "bounce");
this.label[1].attr({ "font-weight": 400 });
}
});
});

Retrieve the selected value from jQUery AutoComplete control

I need two questions answer if possible:
How to set the key\value within the jQuery Autocomplete control.
Retrieve the selected value from the jQuery Autocomplete control once a user selects a school name.
Thank in advance for your help.
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
function RetrieveSchoolsBasedOnSchoolTypeSelected() {
//Item Selected Value
var ItemSelectedValue = $("#selSchoolTypes: option[selected]").val();
$("#example").val("");
$.getJSON("http://devportal2/apps/parisinterndb/_vti_bin/ListData.svc/Schools?$filter=SchoolTypeId eq " + ItemSelectedValue + "", function(DataResults) {
var count = 0;
var resultDataItems = "";
$.each(DataResults.d.results, function(i, result) {
var title = result.Title;
resultDataItems += title +",";
});
resultDataItems += "";
var data = resultDataItems.split(',');
$("#example").autocomplete(data,
{ delay: 10,
minChars: 1,
cacheLength: 10,
autoFill: true
});
});
$("#example").result(findValueCallback).next().click(function() {
$(this).prev().search();
});
}
function findValueCallback(event, data, formatted) {
alert(formatted+" "+data);
}
for getting the selected value,just parse the data paramter in the findValueCallback function.You may need to parse the "data" using split function and all.
ex : if (data != null) {
var model = "";
model = data.toString().split(".")[1];
selectedItem= data.toString().split(".")[0];
}
For setting the key value pair in the autosuggest dropdown,u can use the autocomplete function with a server page which can load data,
$("#txtSearchKey").autocomplete("Lib/ajaxpages/GetModelOptions.aspx", {
minChars: 2,
width: 550,
max: 4,
highlight: false,
scroll: true,
scrollHeight: 300,
formatItem: function(data, i, n, value) {
return "<b>" + value.split(".")[0] + "</b>";
},
formatResult: function(data, value) {
return value.split(".")[0];
}
});
the GetModelOptions.aspx can retun data in the form a string like
1.Alaska \n 2.Mexico \n 3.Michigan \n
and in the javascript u extract it

Resources