I've been trying to get some Google Charts working from some data on a local db. I think I have got the JSON coming out properly now.
{
"cols": [
{
"id": "",
"label": "Inits",
"pattern": "",
"type": "string"
},
{
"id": "",
"label": "SalesVal",
"pattern": "",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "IS",
"f": null
},
{
"v": "1708.6000",
"f": null
}
]
},
{
"c": [
{
"v": "NS",
"f": null
},
{
"v": "1098.8200",
"f": null
}
]
},
{
"c": [
{
"v": "RC",
"f": null
},
{
"v": "458.8200",
"f": null
}
]
}
]
}
And I'm using this as the HTML.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I've gone over it a few times and can't see where I am going wrong.
It occurs since SalesVal column is of number type but the cells contain string values.
According to Format of the Constructor's JavaScript Literal data Parameter:
type [Required] Data type of the data in the column. Supports the
following string values (examples include the v: property, described
later):
'number' - JavaScript number value. Example values: v:7 , v:3.14, v:-55
Having said that you could consider the following options:
Option 1. Modify getData.php endpoint to return a valid json data for google.visualization.DataTable:
"v": "1708.6000" //invalid (current)
"v": 1708.6000 //valid
Option 2
Ensure data column of number type contain JavaScript number value as demonstrated below:
Example
var jsonData = {
"cols": [
{
"id": "",
"label": "Inits",
"pattern": "",
"type": "string"
},
{
"id": "",
"label": "SalesVal",
"pattern": "",
"type": "number"
}
],
"rows": [
{
"c": [
{
"v": "IS",
"f": null
},
{
"v": "1708.6000",
"f": null
}
]
},
{
"c": [
{
"v": "NS",
"f": null
},
{
"v": "1098.8200",
"f": null
}
]
},
{
"c": [
{
"v": "RC",
"f": null
},
{
"v": "458.8200",
"f": null
}
]
}
]
};
google.load('visualization', '1', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(prepareJsonData(jsonData));
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
}
function prepareJsonData(json) {
json.rows.forEach(function(row) {
row.c[1].v = parseFloat(row.c[1].v); //ensure number cell value
});
return json;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Related
my script as below. I have to search the pincode and based on search i have to show locations on map
Ques 1: if i have 2 results for same pincode, then also one marker is coming on the map. i want to show seperate markers.
Ques 2: i want to radar search as well using pincode. like if pincode 07201 and 07202 are very near areas then i should get results for both. i tried using radius in my response, but its not working
<script>
var map;
<!-- var marker; -->
function initialize()
{
var mapOptions = {
center: new google.maps.LatLng('40.71338', '-74.193246'),
zoom: 8,
scrollwheel: false,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
marker = new google.maps.Marker({
position: new google.maps.LatLng(40.71338, -74.193246),
map: map,
});
}
jQuery('#searchPincodeForm').submit(function (event) {
event.preventDefault();
var geocoder = new google.maps.Geocoder();
var search_val=$('#country').val();
jQuery.ajax({
type: 'post',
data:{
'pincode':search_val,
},
url: 'searchPincode.php',
success:function(response){
if(response != ''){
$("#result").html(response).show();
geocoder.geocode({
'address': search_val }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
}
})
} else{
$("#result").html("Sorry Dealer not available at this location. For more information please mail at info#movemaxoil.com").show();
}
}
});
});
</script>
Response i get from geocode:
{
"results": [{
"address_components": [{
"long_name": "07108",
"short_name": "07108",
"types": ["postal_code"]
},
{
"long_name": "Newark",
"short_name": "Newark",
"types": ["locality", "political"]
},
{
"long_name": "Essex County",
"short_name": "Essex County",
"types": ["administrative_area_level_2", "political"]
},
{
"long_name": "New Jersey",
"short_name": "NJ",
"types": ["administrative_area_level_1", "political"]
},
{
"long_name": "United States",
"short_name": "US",
"types": ["country", "political"]
}
],
"formatted_address": "Newark, NJ 07108, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 40.73179289999999,
"lng": -74.1830549
},
"southwest": {
"lat": 40.713114,
"lng": -74.21835
}
},
"location": {
"lat": 40.7235275,
"lng": -74.197388
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 40.73179289999999,
"lng": -74.1830549
},
"southwest": {
"lat": 40.713114,
"lng": -74.21835
}
}
},
"place_id": "ChIJK0xWNjlTwokRLb_3zFLt8zM",
"types": ["postal_code"]
}],
"status": "OK"
}
So the issue is here:
var position = results[0].geometry.location;
map.setCenter(position);
marker.setPosition(position);
Your ajax response may contain more than one location point in it, but in the above code you are using only the first location point results[0].geometry.location here. So instead of results[0] you have to loop through all the results array so that multiple points are mapped on your mark.
when we pass static list of data like [{category":"a","data:"3"},"category":"b","data":"1"}]
then its working fine, but when we pass page url like {"url": "abc.php","format": "json"} in dataprovider section then chart not populate.
This is my code:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider":{ "
url": "abc.php",
"format": "json" },
"labelRadius": -35,
"labelText": "[[percents]]%",
"titleField": "category",
"valueField": "column-1",
"allLabels": [],
"balloon": {},
"legend": {
"enabled": true,
"align": "center",
"markerType": "circle" }
});
Any solution?
Using amCharts with "static" data
If you have "static" data, use the dataProvider setting, like this:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider": [{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}],
// ...
});
Using amCharts with AJAX data
If you want the data to be loaded using AJAX, one way is to make use of amCharts' Data Loader plugin.
Make sure to include it in your HTML:
<script src="amcharts/plugins/dataloader/dataloader.min.js" type="text/javascript"></script>
Leave out the dataProvider setting, and use dataLoader instead.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"dataLoader": {
"url": "abc.php",
"format": "json"
},
// ...
});
Your abc.php file should return valid JSON, like this:
[{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}]
You can find a complete list of options for the Data Loader plugin here: https://www.amcharts.com/kbase/using-data-loader-plugin/.
I am using DataTable to display the data. All the column names with check box is displaying when i click show and hide button. When i uncheck all the column and when i try to check the column name at that time the first column is getting copied or getting displayed in the all the row values.
Following is my code which i written.
$('#datatable_col_reorder').dataTable({
"processing": true,
"sAjaxSource": "<?php echo $config['ajaxUrlPath'];>json.php",
"bFilter" : true,
"fnServerData": function ( sAjaxSource , aoData, fnCallback ) {
aoData.push( { "name": "eventName", "value": $('#eventName').val() });
aoData.push( { "name": "et", "value": $('#Type').val() });
aoData.push( { "name": "vn", "value": $('#address').val() });
aoData.push( { "name": "da", "value": $('#date_added').val() });
aoData.push( { "name": "ti", "value": $('#time_added').val() });
aoData.push( { "name": "st", "value": $('#status').val() });
aoData.push( { "name": "br", "value": $('#status1').val() });
aoData.push( { "name": "cr", "value": $('#status2').val() });
aoData.push( { "name": "pr", "value": $('#spercentage').val() });
// etc
$( "#status2,#address,#spercentage" ).keyup(function() {
var table = $('#datatable_col_reorder').DataTable();
table.ajax.reload();
});
$( "#status,#Type,#date_added,#time_added,#status1,#status2" ).change(function() {
var table = $('#datatable_col_reorder').DataTable();
table.ajax.reload();
});
$.getJSON( sAjaxSource, aoData, function (json) { console.log(json); fnCallback(json) } );
},
"sDom":"<'col-sm-1 col-xs-1 col-md-1 col-lg-1 showHidebutton'C><'dt-toolbar'r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"autoWidth" : true,
"rowCallback": function( nRow, aData, iDisplayIndex ) {
// responsiveHelper_datatable_tabletools.createExpandIcon(nRow);
$('td:eq(0)', nRow).html(''+aData[0]+'');
return nRow;
},
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_col_reorder) {
responsiveHelper_datatable_col_reorder = new ResponsiveDatatablesHelper($('#datatable_col_reorder'), breakpointDefinition);
}
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_col_reorder.respond();
}
});
When i uncheck all and when i try to recheck each checkboxes, at that time the first column values are getting displayed in all other column like type,status,address etc.
Example: Consider Name: XYZ, After deselecting checkboxes if i try to recheck at that time the each column values is showing "XYZ" in status,address columns.
Thanks in advance.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please view my other question here
I am trying to work out how to decode a JSON response from a PHP file.
The JSON is structured as follows:
[{
"id": 1,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
"price": " - "
}
}, {
"id": 2,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
"price": "\u00a3 50 "
}
}, {
"id": 3,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
"price": "\u00a3 50 "
}
}, {
"id": 4,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
"price": " - "
}
}, {
"id": 5,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
"price": "\u00a3 50 "
}
}, {
"id": 6,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
"price": "\u00a3 200 "
}
}, {
"id": 7,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
"price": "\u00a3 9 "
}
}, {
"id": 8,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
"price": "\u00a3 100 "
}
}, {
"id": 9,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
"price": "\u00a3 40 "
}
}, {
"id": 10,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
"price": "\u00a3 10 "
}
}, {
"id": 11,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
"price": " - "
}
}, {
"id": 12,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
"price": "\u00a3 30 "
}
}, {
"id": 13,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
"price": "\u00a3 31 "
}
}, {
"id": 14,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
"price": "\u00a3 25 "
}
}, {
"id": 15,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
"price": "\u00a3 1.0k "
}
}, {
"id": 16,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
"price": "\u00a3 15 "
}
}, {
"id": 17,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
"price": "\u00a3 21 \/hr"
}
}, {
"id": 18,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
"price": "\u00a3 12 "
}
}, {
"id": 19,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
"price": "\u00a3 20 \/hr"
}
}, {
"id": 20,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
"price": "\u00a3 7 \/hr"
}
}]
You can view the current AJAX call on my other question (Link at top of this post).
Could anyone shed some light on how I would decode the JSON array client-side?
I'd like to have a structure like this:
<div class="item">
<div class="title">JSON Title</div>
<div class="price">JSON Price</div>
</div>
Note : from your other question, it is not clear if you always expect a json answer, or if you can receive either of json, html, or xml.
If you always expect json :
$.ajax({ url: ..., data: ...,
dataType: 'json', // <- tell jQuery to expect json,
// and to build a js object from the answer
success : function(obj){
//obj is a regular js object, built from the received json
obj[i].info.title; // <- accessing this piece of data
}
});
If your data is sometimes json, sometimes something else :
success: function(data){
var obj
try {
obj = JSON.parse(data);
// if no exception is thrown, data was a valid json string,
// and obj is a regular js object
obj[i].info.title; // <- accessing this piece of data
} catch (e) {
// Maybe do something on error ?
};
}
You can then build a html string like hsuk suggested :
var html = '';
for(i=0; i < obj.length; i++) {
html += '<div class="item">';
html += '<div class="title">' + obj[i].info.title + '</div>';
html += '<div class="price">' + obj[i].info.price + '</div>';
html += '</div>';
}
alert.html(html).fadeIn();
This is how you do it. What you need is JSON.parse()
test.php
<?php
// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
exit(json_encode(array(
array(
'id' => 1,
'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
),
array(
'id' => 2,
'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
),
array(
'id' => 3,
'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
)
)));
}
?>
<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Make Ajax Request
$.get("test.php?loadData", function(data)
{
// Parse Data
var jsonResults = JSON.parse(data);
// Iterate Through Results
$.each(jsonResults, function(key, value)
{
// Display Data
$('.results').append(
'<div class="item" id="'+ value.info.id +'">'+
'<div class="title">'+ value.info.title +'</div>'+
'<div class="price">'+ value.info.price +'</div>'+
'</div>'
);
});
});
});
</script>
<!-- HTML Page - Display Result -->
<div class="results"></div>
Actually, the funny bit about JSON (JavaScript Object Notation) is that you can use it as is in Javascript.
Meaning, if your JSON string is {"foo": "bar"}, you can directly use it in Javascript like:
var myObject = {"foo": "bar"};
or
var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);
But maybe you better go with JSON.Parse , as eval might be vulnerability if you are parsing User Data, that might not necessarily be in JSON format. (EG. Json data that is sent via HTTP, where the client could mess with ti.)
I know this will be a repetition. But I have tried my best to solve it, all in vain. I am unable to populate even a simple grid panel!!! Obviously I am a newbie in extjs.
My js code is as follows:
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
url: 'compare.php',
fields: ['name', 'area']
});
store.load();
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: 'Name', width: 100, sortable: true, dataIndex: 'name'},
{header: 'Position', width: 100, sortable: true, dataIndex: 'area'}
],
stripeRows: true,
height:250,
width:500,
title:'DB Grid'
});
grid.render('db-grid');
});
and my php is as follows:
<html>
<head>
</head>
<body bgcolor="white">
<?php
$link = pg_Connect('host=my_host port=5432 dbname=da_name user=postgres password=my_password');
$sql = "SELECT name, area FROM \"TABLE\" LIMIT 10";
if (!$link) {
echo "error";
} else {
$result = pg_query($link, $sql);
$rows = array();
$totaldata = pg_num_rows($result);
while($r = pg_fetch_assoc($result)) {
$rows[] = $r;
}
//echo json_encode($rows);
//echo json_encode(array('country' => $rows));
echo '({"total":"'.$totaldata.'","country":'.json_encode($rows).'})';
}
?>
</body>
</html>
And my json is as follows:
[
{
"total": "10",
"country": [
{
"name": "CULTIV",
"area": "1.10584619505971e-006"
},
{
"name": "CULTIV",
"area": "2.87818068045453e-006"
},
{
"name": "CULTIV",
"area": "6.96120082466223e-007"
},
{
"name": "CULTIV",
"area": "1.17171452984621e-007"
},
{
"name": "CULTIV",
"area": "1.25584028864978e-006"
},
{
"name": "CULTIV",
"area": "5.86309965910914e-007"
},
{
"name": "CULTIV",
"area": "4.12220742873615e-007"
},
{
"name": "CULTIV",
"area": "7.59690840368421e-006"
},
{
"name": "CULTIV",
"area": "2.47360731009394e-007"
},
{
"name": "CULTIV",
"area": "4.04940848284241e-005"
}
]
Do I need to set any proxy for this? Actually my application is running on different server than my database.
I have no experience in PostgreSQL but I advice you to use pg_fetch_object() function instead of pg_fetch_assoc() in that case.
Try something like this:
while($obj = $result->pg_fetch_object()) {
$rows = $obj;
}
echo '({"total":"'.$totaldata.'","country":'.json_encode($rows).'})';
Your JSON is malformed. Ext.data.JsonReader (automatically configured when you use a JsonStore) expects a JSON object with a root node, defined in your reader config. The reader should throw an exception if the root is undefined.
So define a root for your JsonReader:
var store = new Ext.data.JsonStore({
url: 'compare.php',
root: 'country', // required!
fields: ['name', 'area']
});
And your JSON should look like this:
{
"total": 10,
"country": [{
"name": "CULTIV",
"area": "6.96120082466223e-007"
},{
...
}]
}