I'm wishing to render multiple charts using mysql data, there will be more or less charts depending on a particular search. I've successfully created a single chart, and my php file echoes the required json format nicely.
Now, what I would like is to be able to loop over an array and draw new charts based on the array vales being parsed to the php which in turn provides different json data to be rendered.
by the way, my javasript is very limited so here goes my code and thoughts:
<script type="text/javascript">
$(function () {
var chart;
var venue = <?php echo json_encode($venue_name); ?>; /* parsed to php file */
var distances = <?php echo json_encode($data); ?>; /* array to be looped over */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue='+venue+'&'+distances
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart = new Highcharts.Chart(options);
});
});
</script>
What I have learnt is that I cannot loop an include php file which has the completed php and jquery...
this will create other charts. every time u want create new chart , u must give new name chart like i do chart2
paste this bellow and it will give you other chart.
<script type="text/javascript">
$(function () {
var chart2;
var venue2 = <?php echo json_encode($venue_name); ?>; /* <---use other variable here of $venue_name */
var distances2 = <?php echo json_encode($data); ?>; /* <---use other variable of $data */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances2, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue2='+venue2+'&'+distances2
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart2 = new Highcharts.Chart(options);
});
});
</script>
Instead of using many variables, you can push your charts to array.
var charts = [];
charts.push(new Highcharts(options));
Then you can avoid of using index etc.
Related
I am trying create map with amCharts using jquery ajax but it doesnt work with ajax.
here my ajax code:
$('button#btn').click(function(){
$('div#ozellikli').html('<center><img src="assets/img/loading.gif" width="200" height="200"/></center>')
$.ajax({
type:'post',
url:'ozellikliAjax.php',
data:$('form#oz').serialize(),
success:function(msg){
$('div#ozellikli').html(msg);
}
});
});
Here my ajax php code:
<?php
include 'config.php';
$html="";
$yil=$_POST['yil'];
$tur=$_POST['tur'];
///HARITAYI CIZ
$sql="SELECT id,il,COUNT(kurum) AS kurum_Say FROM ozellikli GROUP BY id,il ORDER BY kurum_Say";
$result=$baglanti->query($sql);
$mapChart="";
while ($query=$result->fetch(PDO::FETCH_ASSOC)) {
$mapChart.=' { title: "'.$query['il'].':'.$query['kurum_Say'].'", id: "TR'.$query['id'].'",value:'.$query['kurum_Say'].', selectable: true },';
}
$html.='<script type="text/javascript">
AmCharts.ready(function() {
var map;
// *** CREATE MAP ***********************************************************
function createMap(){
map = new AmCharts.AmMap();
map.pathToImages = "http://www.ammap.com/lib/images/";
//map.panEventsEnabled = true; // this line enables pinch-zooming and dragging on touch devices
var dataProvider = {
mapVar: AmCharts.maps.turkeyLow
};
map.areasSettings = {
unlistedAreasColor: "#43B1A9",
rollOverOutlineColor: "#FFFFFF"
};
map.colorSteps=5;
map.valueLegend={
left: 10,
bottom:0,
minValue: "En Az",
maxValue: "En Çok"
};
dataProvider.areas = ['.$mapChart.'];
map.dataProvider = dataProvider;
map.addListener(\'clickMapObject\', function (event) {
// deselect the area by assigning all of the dataProvider as selected object
map.selectedObject = map.dataProvider;
// toggle showAsSelected
event.mapObject.showAsSelected = !event.mapObject.showAsSelected;
// bring it to an appropriate color
map.returnInitialColor(event.mapObject);
var states = [];
for (var i in map.dataProvider.areas) {
var area = map.dataProvider.areas[i];
if (area.showAsSelected) {
states.push(area.title);
}
}
});
map.write("mapdiv");
}
createMap();
});
</script>';
echo $html;
?>
when run the ajax code , script loading with ajax correctly but its not charting to map.
How can I solve this issue?
thanks
If you inject the resources the same way, you need to set manually it's ready state otherwise it won't work. AmCharts listens to the dom loaded event to set following property:
AmCharts.isReady = true;
I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.
I am quite new to objects and OOP. I really don't know how to explain it well but I'll try.
So I am trying to read though JSON with JS, the JSON is passed from PHP. This would be easy if all of the information was on the same html page, but I' am trying something that I am new too.
So let me show my code...
First is the JS which is in app.js
var Donors = function(){
var api = this.list;
$(document).ready(function(){
$.getJSON(api, function(data){
var donorObj = data.payload;
$.each(donorObj, function(i, donor){
//console.log(donor.ign);
});
});
});
}
What I want this part to do is read from the JSON I'm giving it and console.log each name (or donor.ign) when the document is ready.
On the html page, or header.php
<script>
$(function(){
var list = <?php cbProxy(); ?>;
var Dons = new Donors();
Dons.list = list;
});
</script>
the data that's in list is the below JSON. You already know what the rest does, it just passes the JSON to the Donors() function.
JSON example:
{
"code": 0,
"payload": [
{
"time": 1349661897,
"packages": [
"49381"
],
"ign": "Notch",
"price": "15.99",
"currency": "USD"
}
I'm use to just making functions and calling it on the same page or file and this is my first doing this kind of function. How can I get the function to run with the data I sent it so it console.log() each name?
I did try
console.log(Donors());
Which only logged undefined.
New code:
app.js
var Donors = function(api){
this.list = api;
$(document).ready(function(){
$.getJSON(this.list, function(data){
var donorObj = data.payload;
$.each(donorObj, function(i, donor){
console.log(donor.ign);
});
});
});
}
index.php/inline script
<script>
$(function(){
var list = <?php cbProxy(); ?>;
var dons = new Donors(list);
});
</script>
If you execute
var Dons = new Donors();
Dons.list = list;
then you do invoke the constructor function before assigning something to the list property. That means your api variable will be undefined, as long as you haven't defined one on the prototype object from which your Donors inherit. Instead, pass the list as a parameter to the constructor:
function Donors(api) {
this.list = api;
// do something
}
var dons = new Donors(list);
I think it should be this way:
$.getJSON(api, function(data){
$.each(data.payload, function(i, donor){
console.log(donor.ign);
});
});
try this and see if works.
Below is given my sample code. In index.php I define jquery tabs. One of the tabs should open a map (openlayers) and put markers on this map. Latitude and longitude of each marker is taken from MySQL DB. The problem is that I don't know how and where to execute the function put_marker reading data from DB. I know it should be a basic question.
index.php
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs({
ajaxOptions: {
success: function( html ) {
$("#content").html(html);
page_init();
}
}
});
});
</script>
<div id="tabs">
<ul>
<li><span>Administration</span></li>
<li><span>Map</span></li>
</ul>
</div>
map.php
<?php
include_once 'include/DatabaseConnector.php';
$query4="SELECT r.resLatitude, r.resLongitude FROM resources r;";
$result4=DatabaseConnector::ExecuteQueryArray($query4);
foreach ($result4 as $row):
// HERE I HAVE A PROBLEM
//putMarker($row['resLatitude'],$row['resLongitude']);
endforeach;
?>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map, layer;
function page_init(){
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.07833,41.2969).transform( fromProjection, toProjection);
var zoom = 15;
map.addLayer(mapnik);
map.setCenter(position, zoom );
}
function putMarker(latMarca, lonMarca)
{
var lonLat = new OpenLayers.LonLat(lonMarca ,latMarca ).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject());
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
}
</script>
<div id="basicMap" style="width: 100%; height: 100%;">
</div>
Well, you're getting your markers in PHP on the server side. And you're passing them to Javascript on the client side. Two different places.
Actually, there's no need even in JSON manipulations in the simplest case.
In your map.php you can do:
..
echo '<script type="text/javascript">';
echo '$(document).ready(function() {';
foreach ($result4 as $row){
echo 'putMarker('.$row['resLatitude'].','.$row['resLongitude'].');';
}
echo '});';
echo '</script>';
...
These code would be interpreted on the client side as pure JS, but with values being taken from the PHP.
By the way, it's not a good approach to write your code the same way.
Look toward MVC frameworks, where the code and look are separated from each other.
I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity...
<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>
I would like to access these three arrays in Javascript to update my Google Chart dynamically.
<script type="text/javascript">
google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);
var linevol = new Array; // This would be the first array passed from PHP
var loanvol = new Array; // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Cluster');
data.addColumn('number', 'Loans');
data.addColumn('number', 'Lines');
/* create for loops to add as many columns as necessary */
var len = jsonarray.length;
data.addRows(len);
for(i=0; i<len; i++) {
data.setValue(i, 0, ' '+clusters[i]+''); /* x-axis */
data.setValue(i, 1, linevol[i]); /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]); /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>
You probably want them to become Javascript variables. When your php executes, it creates code your web browser then interprets. So you want to define javascript strings using php. For example:
<script type="text/javascript">
var encoded_line_volume = <?php echo json_encode($LineVol) ?>;
var encoded_loan_volume = <?php echo json_encode($LoanVol) ?>;
var encoded_cluster_name = <?php echo json_encode($ClusterLine) ?>;
</script>
Then those variables are accessible to subsequent javascript.
This is how can you generate data dynamically from PHP, generate a JSON formatted output properly and read it from JavaScript (JQuery required) and load it to Google Visulization (Charts) API.
PHP (Server) Side:
function returnData() {
$data = Array ();
$data [] = Array ("Name", "Value");
$data [] = Array ("Apple", 5);
$data [] = Array ("Banana", 3);
header('content-type: application/json');
echo json_encode($data);
}
Javascript (Client) Side:
var jsonData = null;
var jsonDataResult = $.ajax({
url: dataURL,
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
})
});
var data = new google.visualization.arrayToDataTable(jsonData);
This is one of the best examples I did which can help you : its tested and working nicely : Create two pages one called index.php and another one called get_json.php :
This is not exactly the codes you posted but exactly the same idea and it answers the quetion.
the codes for index.php
<html>
<head>
<title>King Musa Graph</title>
<!-- Load jQuery -->
<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: "get_json.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'King Musa'
};
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>
codes for get_json.php
<?php
$data = Array ();
$data [] = Array ("Name", "Value");
$data [] = Array ("PHP", 78);
$data [] = Array ("JAVA", 1000);
$data [] = Array ("HTML", 129);
$table = json_encode($data);
// header('content-type: application/json');
echo $table ; // this line is important it should be not disabled
?>