I'm building a dynamic pie chart to show election results using the Google Visualization API and jQuery, and I had it (sort of) working on my local machine, and wanted to get some feedback, so uploaded it to an external server, now everything I try to load gives me a "No Data" error.
I've got two files, one which gets data from a database and converts it to JSON, and one which displays the visualization, depending on what areas are checked. You can see it here:
http://www2.lichfielddc.gov.uk/sandbox/pie.php?electionid=14
Any ideas where I'm going wrong?
Cheers
Think I may be on to something.
I downloaded it and tested it locally and as you said it works fine. However, in the datasource i was using (data.php) if I put a delay (sleep(1)) it stopped working. I think it was because you were drawing the chart out of the ajax success callback.
Try this:
function drawVisualization() {
$('.poll').click(function() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Party');
data.addColumn('number', 'Votes');
var polls = [];
$('.poll:checked').each(function(){
polls.push(this.value);
});
polls.join(",");
url = "http://www2.lichfielddc.gov.uk/sandbox/piedata.php?pollid=" + polls;
$.getJSON(url, function(d) {
data.addRows(d.length);
var items = [];
var num = 0;
$.each(d, function(i, o) {
console.log(o);
data.setValue(num, 0, o['party']);
data.setValue(num, 1, o['votes']);
num++;
});
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data);
});
});
Stepping through the code: By the time you call the draw() method, the object 'data' has no data in it. This is likely because the modifications to the data object are not in the same scope.
I agree with Tribal that it's a timing issue, because the live version does work sometimes. There's a couple of other lurking bugs, that aren't behind the presenting issue, but ...
polls.join(",");
url = "http://www2.lichfielddc.gov.uk/sandbox/piedata.php?pollid=" + polls;
polls.join() returns a string, it doesn't do the join in-situ. And url isn't being declared as a local variable
Related
My charts loaded via ajax call looks just fine. Currently, whenever user refresh the page, data are loaded from DB server. As those graphs are quite massive, I thought about using SESSION var to store the charts and speed up loading time (all charts are loaded at the same time). Finally, I achieved the goal however I encountered small issue.
Whenever HTML + JS code is served from $_SESSION var, the chart is presented but with no animation effect. In addition flicker effect is visible (scaling). I solved that by setting responsive to false, but this caused issue with labels, being too small to be accepted.
I tried .destroy() option but with no luck (the same flicker effect) :
var myChart = new Chart(ctw, {
type: 'bar',
data: chart_data,
options: chart_options
});
myChart.destroy();
var myChart = new Chart(ctw, {
type: 'bar',
data: chart_data,
options: chart_options
});
Is there any way I can force animation to kick in (regardless if the chart comes from $_SESSION or not) and do not loss responsiveness?
Thank you.
If myChart.destroy() not working. Try myChart.update().
Try update like this:
var myChartData = myChart.data; // need to store in variable first
myChartData = chart_data; // chart_data from $_SESSION var
myChart.data = myChartData;
myChart.update();
Good luck.
I have a class, and an interface in a plugin that I’m building, this interface needs access to functions to list the worpress categories. How to include the files needed to use native wordpress functions. Since the request is made to this interface by ajax. Any Ideas?
this.RequestVideos = function(){
var dados = {};
dados.KeywordUrl = escape($('#termo_pesquisa').val());
dados.categoria = $('#categorias').val();
dados.ordenacao = 'sponsor';
dados.host = Importer.GetSponsors();
dados.duracao = $('#duracao').val();
$.get('/wp-content/plugins/mega-importer/class/Importer.interface.php',dados,function(resposta, status){
Importer.EsconderPainelImportacao();
$('#videos_search').html(resposta);
$('.duracao').mask('00:00:00');
});
}
I need to have access within my Importer.interface.php the native functions of wordpress to be able to retrieve from the database a list of available categories
Thank you any advanced!
Update, Plano B (get all categories e ids the option select existent in my page e send to importer.interface.php)
Wordpress causes me an absurd frustration. Why not to any separation between html, javascript, php, and database. Everything is totally mixed up like a big trash. I spent 20 years of my time as a programmer and a lot of them getting away from writing wordpress plugins. At the end if you still want a documentation with examples of functioning, you will encounter text all in English where the language barrier will disrupt the total understanding and the worst without any functional example that clarifies your doubt. Thank you for your work but I'm going to Plan B creative.
this.GetAllCategorias = function(){
var obj = [];
var ids = new Array();
var labels = new Array();
$("#categorias option").each(function(){
ids.push($(this).val());
labels.push($(this).text());
});
obj.push(ids.join());
obj.push(labels.join());
return JSON.stringify(obj);
}
I'm a newbie web developer diving into Backbone for the first time. One major question I've been grappling with (actually spending a lot of the last 2 days researching to no avail) is how exactly Backbone communicates with the server.
In my previous projects, I've been able to fetch data from my database using PHP and jQuery's $.getJSON method. I'm also able to do this when I use Backbone (ex. myCollection.url = "todos.php"). However, in every single tutorial, documentation, example code I've looked at, the url for the collection is always set as a directory and the urlRoot is directory/id (ex. myCollection.url = "/todos" and myModel.urlRoot = "/todos/5".
My question is how exactly is this managed? It seems a lot cleaner than the traditional way I was doing by adding GET parameters to my calls. At first I thought this was routing, but that seems to be only related to setting browser history and stuff. Some of the source code I've looked at uses SLIM PHP and Rails (neither of which I've used) but I have no clue how any of the parts fit together.
Backbone has its own api for communicating with server, such as fetch, save, destory.In fact, these methods do the same things with jQuery's $.ajax. For example, you use backbone's fetch in this way:
var UserModel = Backbone.Model.extend({
url : "rootURL/user",
});
var user = new UserModel;
user.fetch(
data:{
userId : 1, //the webservice will be: rootURL/user?userId=1 GET;
}
success:function(model, response, options){
//callback
},
error:function(model, response, options){
//callback
},
);
But you can also use the same way as in the jQuery to communicate with server in backbone's application.For example:
var UserView = Backbone.View.extend({
render: function(){
//do something
}
getUser: function(userId){
$.get("rootURL/user",
{ userId : userId},
success:function(data){
//callback
}
);
}
});
I am using AngularJS 1.0, PHP, and mysql with localhost on my Mac.
I have a very simple mysql database: "cats". It has one table called "kittens". The table has two columns, "id" and "name". There are three kittens in the database with names Larry, Curly, and Moe.
Now, I have some simple PHP code which opens the dbase, gets the three records, and returns them in JSON like this:
[{"id":"1","name":"Larry"},{"id":"2","name":"Curly"},{"id":"3","name":"Moe"}]
I used the latest angular-seed and set up a project in Eclipse. In app.js I wrote this:
'use strict';
angular.module('Cats', ['ngResource','Cats.filters', 'Cats.services', 'Cats.directives'])
I put my PHP code in the services folder and named it "index.php". If I navigate to that services/index.php in my browser using localhost on the Mac, I get back the JSON above. So far everything is cool.
Now - ALL I WANT TO DO (!famous last words ;) is connect to the PHP service I have and display the contents of that Cats table on my main index page using my AngularJS project. Plain old text, no tables, just bind to the available resource and display it.
I have tried all manner of demos online (many are out of date). Can anyone show me one simple, current way to do this? For the life of me I have all kinds of AngularJS demos working but none of them does this simple task in a way I can understand.
Thank you in advance.
This should also work. It's significantly fewer lines of code, but note that any error handling has been removed:
function FetchCtrl($scope, $resource) {
var services = $resource('../services/index.php');
$scope.data = services.query();
}
FetchCtrl.$inject = ['$scope', '$resource'];
Normally I would have used the built in .get() method on the $resouce but your response is in the form of an Array, which .query() supports by default.
You can find the documentation on $resource here
OK. Solved it. First, copied and added a controller I found in one of the examples:
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url='../services/index.php';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
Then, I added a route controller to my module:
var module = angular.module('Cats', ['ngResource','Cats.filters', 'Cats.services', 'Cats.directives'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/main', {templateUrl: 'partials/partial1.html', controller: MyCtrl1});
Finally, on that partial1.htm page, I added this:
<div ng-init="fetch()">
{{data}}
</div>
Now when I go to that page in the browser, I can see the entire database dumped out in JSON. Ahhhh. Clearly there are many more sophisticated things to try, etc etc but I needed this simple result so I could be certain that I did in fact have a model arriving when summoned. Angular dies silently in many cases, so a visible result was quite helpful.
One gotcha: be careful that the php file is executable by more than yourself as user. I don't know the name of the user that AngularJS implements but I had to chmod 644 index.php so the app could use it.
I hope that helps someone.
i am thinking of building an android app in appcellerators titanium application, and i have a question, the website which the app is for is built using php/mysql, and what i am wondering is, as titanium works using javascript, html and css only, is there a way i can pull the data dynamically from my database using javascript?
if this has already been posted I'm sorry i searched and couldnt find it :S
With PHP, take your database response array and encode it like this:
<?php
json_encode($db_array);
?>
More information:
http://php.net/manual/en/function.json-encode.php
Note that you'll need PHP 5.2 or above in order to have the built in JSON functions for PHP.
In Titanium, you want to open a XHR (or network handler) to grab the data:
var xhr = Ti.Network.createHTTPClient();
var.onload = function()
{
try
{
data = JSON.parse(this.responseText);
}
catch (excp)
{
alert('JSON parse failed');
}
// you should handle your network async, meaning you should handle any renders or any post elements here. if you make it sync, you'll cause all other handlers and functions to work improperly (like click events, etc).
}
xhr.open("GET", "your url here");
xhr.send();
You can access the the data array by simply calling data[0].some_col;
Try reading tutorial about using SQLite databases in Titanium applications
I'm sorry it's for iPhone, but in basics the principle is the same
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite/
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-part-2/
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-%E2%80%93-part-3/
using is like this:
var db = Ti.Database.install('../products.sqlite','products');
var rows = db.execute('SELECT DISTINCT category FROM products');
Documentation:
http://developer.appcelerator.com/apidoc/mobile/1.3/Titanium.Database-module
The best way would be to use JSON using json_encode if you were accessing the database from the website. If you were trying to use a local database then use sqlite.
You need to build an webservice on your website, and pull the data in with Titanium.Network.HTTPClient
You can see it here: http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.Network.HTTPClient-object
An example would be:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
var data = this.responseText; //response is here
// do your thing within this scope, or call a function/event from here
}
var url = 'http://www.google.nl';
xhr.open("GET", url); // or "POST"
xhr.send();
Note that the data variable is not accessable outside the scope, even if it is a global. Call your function from within the scope
In the app you could either use SQLite, or don't store the data. Whatever suits your application best